欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Restful 示例

程序员文章站 2022-06-17 16:55:09
...

服务器端代码

创建SpringBoot项目

Maven依赖

	<dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.10</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

application.yml

server:
  port: 80
  servlet:
    context-path: /demo

返回统一格式数据相关

ResultCode.java

public enum ResultCode {
    /* 成功状态码 */
    SUCCESS(200, "操作成功"),

    /**
     * 客户端错误
     */
    CLIENT_FAIL(400, "客户端错误"),

    /**
     * 服务器端错误
     */
    SERVER_FAIL(500, "服务器端错误"),

    PARAM_IS_INVALID(40001, "参数无效"),
    USER_NOT_LOGGED_IN(40002, "用户未登录,请先登录"),

    SYSTEM_INNER_ERROR(50001, "系统繁忙,请稍后重试"),

    PERMISSION_TOKEN_EXPIRED(70004, "token已过期"),
    PERMISSION_TOKEN_INVALID(70006, "无效token"),
    PERMISSION_SIGNATURE_ERROR(70007, "签名失败");

    /**
     * 操作代码
     */
    int code;
    /**
     * 提示信息
     */
    String msg;

    ResultCode(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

Result.java

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> {
    /**
     * 请求响应状态码(200、400、500)
     */
    private int code;
    /**
     * 请求结果描述信息
     */
    private String msg;
    /**
     * 请求结果数据
     */
    private T data;

    public Result(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Result(ResultCode resultCode) {
        this.code = resultCode.getCode();
        this.msg = resultCode.getMsg();
    }
}

ResultUtil.java

public class ResultUtil {
    /**
     * 操作成功,只返回结果码和提示信息
     * 用于删除、修改、新增接口
     * @return
     */
    public static Result success() {
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 操作成功,只返回结果码和具体的数据,但不返回提示信息
     * 用于删除、修改、新增接口
     * @return
     */
    public static Result success(int code, String msg) {
        return new Result(code, msg);
    }

    /**
     * 操作成功,返回具体的数据、结果码和提示信息
     * 用于数据查询接口
     * @param data
     * @return
     */
    public static Result success(Object data) {
        Result<Object> result = new Result(ResultCode.SUCCESS);
        result.setData(data);
        return result;
    }

    /**
     * 操作成功,返回具体的数据、结果码和提示信息
     * 用于数据查询接口
     * @param code
     * @param msg
     * @param data
     * @return
     */
    public static Result success(Integer code, String msg, Object data) {
        return new Result<>(code,msg,data);
    }


    /**
     * 操作失败,只返回结果码和提示信息
     *
     * @param resultCode
     * @return
     */
    public static Result fail(ResultCode resultCode) {
        return new Result(resultCode);
    }

    /**
     * 操作失败,只返回指定的结果码和具体的数据,但不返回提示信息
     *
     * @return
     */
    public static Result fail(int code, String msg) {
        return new Result(code, msg);
    }

    /**
     * 操作失败,返回具体的数据、结果码和提示信息
     *
     * @param code
     * @param msg
     * @param data
     * @return
     */
    public static Result fail(Integer code, String msg, Object data) {
        return new Result<>(code,msg,data);
    }
}

实体类

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
public class Dept {
    private Integer deptno;
    private String dname;
    private String loc;
}

数据库模拟类

public class DeptTable {
    private static ArrayList<Dept> depts = new ArrayList<>();

    static {
        depts.add(new Dept(10, "ACCOUNTING", "CHICAGO"));
        depts.add(new Dept(20, "RESEARCH", "DALLAS"));
        depts.add(new Dept(30, "SALES", "CHICAGO"));
        depts.add(new Dept(40, "OPERATIONS", "BOSTON"));
    }

    public static boolean insert(Dept dept) {
        boolean res = depts.add(dept);
        return res;
    }

    public static boolean update(Dept dept) {
        Integer deptno = dept.getDeptno();
        boolean flag = false;
        for (int i = 0; i < depts.size(); i++) {
            Dept temp = depts.get(i);
            if (temp.getDeptno().equals(deptno)) {
                depts.set(i, dept);
                flag = true;
            }
        }
        return flag;
    }

    public static boolean delete(Integer deptno) {
        boolean flag = false;
        for (int i = 0; i < depts.size(); i++) {
            Dept dept = depts.get(i);
            if (dept.getDeptno().equals(deptno)) {
                depts.remove(i);
                flag = true;
            }
        }
        return flag;
    }

    public static Dept select(Integer deptno) {
        for (int i = 0; i < depts.size(); i++) {
            Dept dept = depts.get(i);
            if (dept.getDeptno().equals(deptno)) {
                return dept;
            }
        }
        return null;
    }

    public static void output() {  //输出所有数据,查看测试结果用
        for (Dept dept : depts) {
            System.out.println(dept);
        }
    }
}

Controller

@Slf4j
@RestController
@RequestMapping("/rest")
public class DeptController {
    //增加Dept ,使用POST方法
    @PostMapping(value = "/dept")
    public Result saveDept(@RequestBody Dept dept) {
        boolean res = DeptTable.insert(dept);
        log.info("saveDept:{}", dept);
        DeptTable.output();
        if (res) {
            return ResultUtil.success(dept);
        } else {
            return ResultUtil.fail(ResultCode.SERVER_FAIL);
        }
    }

    //更新Dept,使用PUT方法
    @PutMapping(value = "/dept")
    public Result updateDept(@RequestBody Dept dept) {
        boolean flag = DeptTable.update(dept);//表示用户要删除的deptno不存在
        log.info("updateDept:{}", dept);
        DeptTable.output();
        if (flag) {
            return ResultUtil.success(dept);
        } else {
            return ResultUtil.fail(ResultCode.SERVER_FAIL);
        }
    }

    //删除Dept,使用DELETE方法
    @DeleteMapping(value = "/dept/{deptno}")
    public Result deleteDept(@PathVariable Integer deptno) {
        boolean flag = DeptTable.delete(deptno);
        log.info("deleteDept:{}", deptno);
        DeptTable.output();
        if (flag) {
            return ResultUtil.success(deptno);
        } else {
            return ResultUtil.fail(ResultCode.CLIENT_FAIL);
        }
    }

    //获取Dept,使用GET方法
    @GetMapping(value = "/dept/{deptno}")
    public Result getDept(@PathVariable Integer deptno) {
        Dept dept = DeptTable.select(deptno);
        if (dept != null) {
            return ResultUtil.success(dept);
        } else {
            return ResultUtil.success(ResultCode.SERVER_FAIL);
        }
    }

}

测试部分

启动项目,采用Restful toolkit进行测试
Restful 示例

/rest/dept

Restful 示例
Restful 示例

/rest/dept

Restful 示例
Restful 示例

/rest/dept/{deptno}

Restful 示例
Restful 示例
Restful 示例

/rest/dept/{deptno}

Restful 示例
Restful 示例