博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ARTS打卡计划第一周-Tips-ControllerAdvice的使用
阅读量:6929 次
发布时间:2019-06-27

本文共 3314 字,大约阅读时间需要 11 分钟。

通常在开发具体项目过程中我们可能会面临如下问题:

  1. 统一所有的json返回结果
  2. 统一处理所有controller中的异常,并且给不同异常不同的返回状态值
  3. 统一对返回的接口做数据校验或者加密,防止篡改

在spring中的处理方式是使用@RestControllerAdvice注解。下面是一个例子,可以将所有的controller中的返回结果,包装成一个CommonResponse。

@RestControllerAdvicepublic class CommonResponseDataAdvice implements ResponseBodyAdvice {    @Override    @SuppressWarnings("all")    public boolean supports(MethodParameter methodParameter,                            Class
> aClass) { if (methodParameter.getDeclaringClass().isAnnotationPresent( IgnoreResponseAdvice.class )) { return false; } if (methodParameter.getMethod().isAnnotationPresent( IgnoreResponseAdvice.class )) { return false; } return true; } @Nullable @Override @SuppressWarnings("all") public Object beforeBodyWrite(@Nullable Object o, MethodParameter methodParameter, MediaType mediaType, Class
> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) { CommonResponse response = new CommonResponse<>(0, ""); if (null == o) { return response; } else if (o instanceof CommonResponse) { response = (CommonResponse) o; } else { response.setData(o); } return response; }}

  上述代码中定义了一个注解IgnoreResponseAdvice,如果controller的类或者方法有这个注解就不做处理。下面这个例子展现的是如何在controller抛出异常的时候,自动包装成为commonRespons。

@RestControllerAdvicepublic class GlobalExceptionAdvice {    @ExceptionHandler(value = ParamException.class)    public CommonResponse
handlerParamException(HttpServletRequest req, ParamException ex) { CommonResponse
response = new CommonResponse<>(400, "param error"); response.setData(ex.getMessage()); return response; } @ExceptionHandler(value = BusinessException.class) public CommonResponse
handlerBusinessException(HttpServletRequest req, BusinessException ex) { CommonResponse
response = new CommonResponse<>(500, "business error"); response.setData(ex.getMessage()); return response; } @ExceptionHandler(value = SystemException.class) public CommonResponse
handlerSystemException(HttpServletRequest req, SystemException ex) { CommonResponse
response = new CommonResponse<>(700, "system error"); response.setData(ex.getMessage()); return response; }}

  对比下面的controller能更清楚的明白如何使用。

@RestControllerpublic class IndexController {		@RequestMapping("/")	String home() {		return "Hello World!";	}	@IgnoreResponseAdvice	@RequestMapping("/hi")	String hi() {		return "Hello World!";	}	@RequestMapping("/param")	String param() throws Exception {		throw new ParamException("参数错误");	}	@RequestMapping("/business")	String business() throws Exception {		throw new BusinessException("业务错误");	}	@RequestMapping("/system")	String system() throws Exception {		throw new SystemException("系统错误");	}}

  详细的代码见 

  特别的,这个文章提供了几种其他的解决方案:

 

转载于:https://www.cnblogs.com/dongqiSilent/p/10742803.html

你可能感兴趣的文章
HTTP 错误405.0 - Method Not Allowed
查看>>
MIFARE系列7《安全》
查看>>
Qt工程转化为Vs工程
查看>>
剑指offer 例题
查看>>
Caffe学习系列(2):数据层及参数
查看>>
POJ1300(欧拉回路)
查看>>
Windows下cpu使用的监控
查看>>
怎样将baidu地图中的baidu logo 去掉
查看>>
WebService学习总结——调用第三方提供的webService服务
查看>>
设置vs2008代码区的背景色
查看>>
ServerSocket 默认邦定IP
查看>>
谈谈前端『新』技术
查看>>
(白书训练计划)UVa 120 Stacks of Flapjacks(构造法)
查看>>
删除反复字符
查看>>
解决Win10服务主机本地系统网络受限
查看>>
【POJ 3176】Cow Bowling(DP)
查看>>
SQL 存储过程入门(事务)(四)
查看>>
培训课程大纲
查看>>
Atitit. Ati IDE 开发平台的第一版规划
查看>>
总结oninput、onchange与onpropertychange事件的用法和区别
查看>>