springboot实现restful

1.首先自定义一个接口返回的格式java

这里引入了lombok, org.projectlombok:lombok   这样在class上加入@Data注解就不用再生成getter,setter方法了,很方便,也很节省代码spring

@Data
public class ResponseResult {


    String message;

    Object data;


    public static ResponseResult success(Object data, String msg) {
        ResponseResult result = new ResponseResult();
        result.setMessage(msg);
        result.setData(data);
        return result;
    }


}

2.springboot实现restful格式,这里采用了ResponseEntity,其中ResponseEntity 是在 org.springframework.http.HttpEntity 的基础上添加了http status code(http状态码),用于RestTemplate以及@Controller的HandlerMethod。它在Controoler中或者用于服务端响应时,做用是和@ResponseStatus与@ResponseBody结合起来的功能同样的。用于RestTemplate时,它是接收服务端返回的http status code 和 reason的。springboot

@RequestMapping("/user")
@Controller
public class UserController{


@Autowired
UserService userService


    @RequestMapping(value = "/queries", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<ResponseResult> findUserList(@RequestBody InputDto inputDto, HttpServletResponse response) throws AppException {
        List<User> userList=userService.findUsers();
        return ResponseEntity.ok().body(ResponseResult.success(userList, ""));

        //return ResponseEntity.badRequest().body(ResponseResult.success(userList, ""));

        //return ResponseEntity.accepted().body(null);


    }


//当查询条件过多时,能够采用post方式来实现,固然最好的方式是查询的所有用get方式

}

接口返回状况以下:错误码单独出来,body体是自定义的ResponseResult,这个能够自行设定,也能够不要这个对象。服务器

 

3.restful的经常使用错误码restful

200 OK  [GET]:服务器成功返回用户请求的数据,该操做是幂等的(Idempotent)。
201 CREATED - [POST/PUT/PATCH]:用户新建或修改数据成功。
202 Accepted - [*]:表示一个请求已经进入后台排队(异步任务)
204 NO CONTENT - [DELETE]:用户删除数据成功。
400 INVALID REQUEST - [POST/PUT/PATCH]:用户发出的请求有错误,服务器没有进行新建或修改数据的操做,该操做是幂等的。
401 Unauthorized - [*]:表示用户没有权限(令牌、用户名、密码错误)。
403 Forbidden - [*] 表示用户获得受权(与401错误相对),可是访问是被禁止的。
404 NOT FOUND - [*]:用户发出的请求针对的是不存在的记录,服务器没有进行操做,该操做是幂等的。
406 Not Acceptable - [GET]:用户请求的格式不可得(好比用户请求JSON格式,可是只有XML格式)。
410 Gone -[GET]:用户请求的资源被永久删除,且不会再获得的。
422 Unprocesable entity - [POST/PUT/PATCH] 当建立一个对象时,发生一个验证错误。
500 INTERNAL SERVER ERROR - [*]:服务器发生错误,用户将没法判断发出的请求是否成功。
相关文章
相关标签/搜索