使用
@ControllerAdvice
&ResponseBodyAdvice
拦截Controller方法默认返回参数,统一处理返回值/响应体
1、Controller代码
以下是Controller查询方法源码:
/**
* controller
*
* @author yclimb
* @date 2018/6/29.
*/
@RestController
@RequestMapping("/manage/user")
public class TestController {
private Logger logger = LoggerFactory.getLogger(TestController.class);
/**
* 通过会员id获取会员信息及详情
*
* @param id 会员id
* @return app msg
*
* @author yclimb
* @date 2018/6/29
*/
@GetMapping("/edit/{id}")
public AppMessage edit(@PathVariable Integer id) {
if (null == id) {
return AppMessage.error(-3, "会员ID不能为空");
}
// 查询会员对象
User user = userService.queryById(id);
if (user == null) {
return AppMessage.error(-3, "根据会员ID未查询到对应会员");
}
return AppMessage.success(user);
}
}
2、拦截处理器
下面已经封装好了一个拦截处理类以供参考:
package com.yclimb.test;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
/**
* 拦截Controller方法默认返回参数,统一处理返回值/响应体
*
* @author yclimb
* @date 2018/6/29
*/
@ControllerAdvice
public class TestResponseBodyAdvice implements ResponseBodyAdvice {
@Override
public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
System.out.println("TestResponseBodyAdvice==>beforeBodyWrite:" + o.toString() + ","
+ methodParameter);
return o;
}
@Override
public boolean supports(MethodParameter methodParameter, Class aClass) {
return true;
}
}
3、测试方法
Controller:
ResponseBodyAdvice:
结语
到此本文就结束了,关注公众号查看更多推送!!!