??????spring boot??????restful api

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了??????spring boot??????restful api相关的知识,希望对你有一定的参考价值。

?????????art   map   exce   details   ==   article   ??????   runtime   ??????   

1 ??????????????????produces = "application/json"

??????????????????json?????????response???

2 ????????????????????????

???????????????????????????????????????

??????????????????ResponseEntity?????????????????????

3 ???????????????????????????

3.1 ????????????Exception??????

public class UserNotFountException extends RuntimeException{
    private String userId;

    public UserNotFountException(String userId) {
        this.userId = userId;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }
}

3.2 ???????????????ExceptionHandler

@ExceptionHandler(UserNotFountException.class)
public ResponseEntity<Error> UserNotFound(UserNotFountException e){
String userId = e.getUserId();
Error error = new Error(4 , "User ???"+userId+") not found");
return new ResponseEntity<Error>(error,HttpStatus.NOT_FOUND);
}

 


3.3 ????????????????????????????????????

@RequestMapping(value = "/{id}",method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<User> getUserById (@PathVariable("id") String id){
//?????????????????????
initUserInfo();
User result = users.get(id);
HttpStatus status = result != null ? HttpStatus.OK : HttpStatus.NOT_FOUND;
if(result == null){
throw new UserNotFountException(id);
}
return new ResponseEntity<User>(result,status);
}

 

 

 

 

 

???????????????

https://blog.csdn.net/github_34889651/article/details/53705306

 

























以上是关于??????spring boot??????restful api的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot入门

Spring Boot入门

Spring Boot 统一结果封装

rest-spring-boot-starter

《Pro Spring Boot 2》第五章:Data Access with Spring Boot

Spring Boot Guides Examples(1~3)