怎么包裹RestController的返回值?

lonsdale8734 2016-04-10 11:20:26
例如原始返回值是 ”This is response“,
返回

{
"status":1,
"content":"This is response”
}

异常时返回

{
"status":0,
"content":"exception message”
}

使用spring aop没有实现预期的结果

@Component
@Aspect
@EnableAspectJAutoProxy
public class ResponseWrapping {

@Pointcut("within(@org.springframework.web.bind.annotation.RestController *)")
public void restPointcut() {
}

@Pointcut("execution(* *(..))")
public void anyMethodPointcut() {
}

@AfterReturning(value = "restPointcut() && anyMethodPointcut()", returning = "response")
public Object wrapResponse(Object response) {
Map<String, Object> result = new HashMap<>();
result.put("status", 1);
result.put("data", response);
return result;
}

@AfterThrowing(value = "restPointcut() && anyMethodPointcut()", throwing = "exception")
public Object wrapException(RuntimeException exception) {
Map<String, Object> result = new HashMap<>();
result.put("status", 0);
result.put("msg", exception.getMessage());
return result;
}
}

测试用controller

@RestController
@RequestMapping("/admin")
public class TestController {

@RequestMapping(value = "/test", method = RequestMethod.GET)
public Object test(@RequestParam("test") int test) {
if (test == 0)
throw new RuntimeException("This is an exception test response");
else
return "This is normal test response";
}
}
...全文
397 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
scmod 2016-04-11
  • 打赏
  • 举报
回复
@RestController不用加@ResponseBody了吧 @Afterxxx这个是方法已经结束了才会调用的,用Around看看有用不..
家里敷泥呀 2016-04-11
  • 打赏
  • 举报
回复
方法上添加@responsebody注解,然后返回json或javabean就好了

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧