springboot实现rest风格api简单demo教程附源码背景
框架搭建
代码实现
定义统⼀返回实体,包含响应结果,响应数据,作为api的统⼀返回结果。
public class JsonResponse {
private ResObj resObj;
private Object data;
public JsonResponse success(){
return this;
}
public JsonResponse success(Object obj){
this.data = obj;
return this;
}
public JsonResponse failure(String message){
return this;
}
public ResObj getResObj(){
return resObj;
}
public void setResObj(ResObj resObj){
}
public Object getData(){
return data;
}
public void setData(Object data){
this.data = data;
}
}
public class ResObj  {
private String message;
private String resCode;
public ResObj(String message, String resCode){
}
public ResObj(String resCode){
}
public String getMessage(){
return message;
}
public void setMessage(String message){
}
public String getResCode(){
return resCode;
}
public void setResCode(String resCode){
}
}
编写dao层
public interface UserMapper {
List<User>findAllUsers();
User findUserById(@Param("userId")String userId);
int updateUserById(User u);
int deleteUserByUserId(@Param("userId")String userId); int insertUser(User u);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.jj.blog.dao.UserMapper">
<resultMap id="usersResult"type="User">
<result property="userId"column="USERID"/>
<result property="userName"column="USERNAME"/>
springboot aop<result property="userPassword"column="PASSWORD"/>
</resultMap>
<select id="findAllUsers"resultMap="usersResult">
SELECT USERID, USERNAME,PASSWORD FROM T_USER_2019
</select>
<select id="findUserById"resultMap="usersResult"parameterType="java.lang.String">
SELECT USERID, USERNAME,PASSWORD FROM T_USER_2019
WHERE USERID = #{userId}
</select>
<update id="updateUserById">
UPDATE  T_USER_2019
<set>
<if test="userPassword != null and userPassword.length()>0">PASSWORD = #{userPassword},</if>
</set>
WHERE
USERID = #{userId}
</update>
<delete id="deleteUserByUserId"parameterType="java.lang.String">
DELETE FROM T_USER_2019 WHERE USERID = #{userId}
</delete>
<insert id="insertUser"parameterType="com.ity.User">
INSERT INTO T_USER_2019 (USERID,USERNAME,PASSWORD)
VALUES  (#{userId},  #{userName},  #{userPassword})
</insert>
</mapper>
service层(略)
controller层 根据不同请求⽅式进⾏增删改查
//restcontroller = controller + responseBody 将返回结果转换问json格式
@RestController
public class UserController {
@Autowired
UserServie userServie;
//根据不同请求⽅式进⾏增删改查
@PostMapping(value ="/user")
public JsonResponse createUser(@RequestBody User u){
userServie.insertUser(u);
return new JsonResponse().success(u);
}
@GetMapping(value ="/users")
public JsonResponse getUserList(){
return new JsonResponse().success(userServie.findAllUsers());
}
@GetMapping(value ="/user/{userId}")
public JsonResponse getUser(@PathVariable("userId") String userId){
User u = userServie.findUserById(userId);
return new JsonResponse().success(u);
}
@DeleteMapping(value ="/user/{userId}")
public JsonResponse deleteUser(@PathVariable("userId") String userId){
userServie.deleteUserByUserId(userId);
return new JsonResponse().success();
}
@PutMapping(value ="/user")
public JsonResponse updateUser(@RequestBody User u){
userServie.updateUserById(u);
return new JsonResponse().success(u);
}
}
使⽤aop对异常做统⼀处理
创建切⾯类ExceptionAspect.class。添加ControllerAdvice注解增强控制器和ResponseBody注解
@ControllerAdvice// 控制器增强
@ResponseBody
public class ExceptionAspect {
private static final Logger log = Logger(ExceptionAspect.class);
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public JsonResponse handleHttpMessageNotReadableException(
HttpMessageNotReadableException e){
<("could_not_", e);
return new JsonResponse().failure("could_not_read_json");
}
/
**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler({MethodArgumentNotValidException.class})
public JsonResponse handleValidationException(MethodArgumentNotValidException e){        ("parameter_", e);
return new JsonResponse().failure("parameter_validation_exception");
}
/**
* 405 - Method Not Allowed。HttpRequestMethodNotSupportedException
* 是ServletException的⼦类,需要Servlet API⽀持
*/
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public JsonResponse handleHttpRequestMethodNotSupportedException(
HttpRequestMethodNotSupportedException e){
<("request_method_", e);
return new JsonResponse().failure("request_method_not_supported");
}
/**
* 415 - Unsupported Media Type。HttpMediaTypeNotSupportedException
* 是ServletException的⼦类,需要Servlet API⽀持
*/
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler({ HttpMediaTypeNotSupportedException.class})
public JsonResponse handleHttpMediaTypeNotSupportedException(Exception e){
<("content_type_", e);
return new JsonResponse().failure("content_type_not_supported");
}
/**
* 500 - Internal Server Error
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public JsonResponse handleException(Exception e){
<("Internal ", e);
return new JsonResponse().failure("Internal Server Error");
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。