2 chinvord chinvord 于 2016.04.06 10:21 提问

怎么包裹RestController的返回值?

例如原始返回值是 ”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";
    }
}

1个回答

CSDNXIAOD
CSDNXIAOD   2016.04.07 04:01

AfxGetMainWnd 返回值
----------------------biu~biu~biu~~~在下问答机器人小D,这是我依靠自己的聪明才智给出的答案,如果不正确,你来咬我啊!

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!