【问题标题】:Get json content of request and response on annotated Spring Controller在带注释的 Spring Controller 上获取请求和响应的 json 内容
【发布时间】:2016-06-15 13:19:19
【问题描述】:

我想构建一个库,将请求和响应的 Json 内容保存在带注释的 Spring 控制器上。

所以我建立了自己的注解 @Foo 并将它放在一些控制器上:

    @Foo
    @RequestMapping(method = RequestMethod.POST, value = "/doSomeThing", produces = {
            MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_XML_VALUE,
            MediaType.APPLICATION_XML_VALUE})
    public ResponseEntity<T> doSomething(/*some parameters*/) {
        T t = doSomeJob(T.class);
        return new ResponseEntity<T>(t, HttpStatus.OK);
}

我不保证请求和响应在 Contreller 的参数中! 而且我在 @AfterReturning AOP 切入点内对任何具有该注释的控制器进行了调用。

@Component
@Aspect
public class XYInterceptor
@AfterReturning(
            pointcut = "execution(@my.annotation.Foo)")
            public void doSomethingWithJsonContent(JoinPoint joinPoint) throws Throwable {

            //How can i get json value of request and response here?    
}   

如何获取 json 格式的请求和响应内容(例如发送/返回给客户端)?

感谢您的帮助!

【问题讨论】:

标签: json spring annotations request aop


【解决方案1】:

好吧,您需要通过注入的类成员、方法参数或方法返回值以某种方式从控制器方法访问请求和响应。它必须在某处。因为您没有解释您打算从哪里获得它,所以我可以发布一个一般性答案,展示如何从@AfterReturning 建议中确定方法参数和返回值。如果您用更详细的信息更新问题,我也可以相应地更新答案。

我的切入点(注释掉的那个也可以,选择你喜欢的那个)将返回值绑定到一个参数,并假设请求和响应都是String 类型。随意替换为您最喜欢的。此外,如果您知道参数存在并且知道其(超级)类型,则可以将拦截方法中的参数(无论它在签名中的哪个位置)绑定到类型化的通知方法参数。这样您就可以摆脱getArgs() 上的缓慢而丑陋的循环。

//@AfterReturning(pointcut = "execution(@my.annotation.Foo * *(..))", returning = "response")
@AfterReturning(pointcut = "@annotation(my.annotation.Foo)", returning = "response")
public void interceptRequest(String response, JoinPoint thisJoinPoint) {
    System.out.println(thisJoinPoint);
    for (Object arg : thisJoinPoint.getArgs()) {
        if (arg instanceof String)
            System.out.println("  request = " + arg);
    }
    System.out.println("  response = " + response);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 2015-06-20
    • 2019-05-25
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    相关资源
    最近更新 更多