当前位置: 首页 > 知识库问答 >
问题:

Spring MVC 3.2@ResponseBody拦截器

家经纶
2023-03-14

在我们的应用程序中,我们使用JSON进行请求和响应。控制器方法用@RequestBody()注释。返回的对象,例如TransferResponse。我想从@ResponseBody中找到这个对象。我已经设置了一个拦截器postHandle方法:

@Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView modelAndView) throws java.lang.Exception

    {
....

}

那么如何在这个postHandle方法中获取JSON呢?

提前感谢GM

共有3个答案

单修德
2023-03-14

因为问题已经发布,所以在SpringMVC4.1中添加了ResponseBodyAdvice。此接口允许应用程序在应用转换器之前更改或完全更改车身。拦截请求的文档也专门针对此问题进行了更新:

请注意,HandlerInterceptor的postHandle方法并不总是非常适合与@响应体和响应实体方法一起使用。在这种情况下,HttpMessageConzer在调用postHandle之前写入并提交响应,这使得无法更改响应,例如添加标头。相反,应用程序可以实现响应身体建议,并将其声明为@控件建议bean或直接在请求映射处理适配器上配置它。

金阳曜
2023-03-14

我终于有了一个有效的(但不优雅的)解决方案。我认为可以有更好的解决方案,但我找不到。

首先,我创建了一个封装有效负载的请求和响应包装器,使我的请求输入流和响应输出流可重用和重写。我需要在我的过滤器中使用它来操作请求和响应有效负载。

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import org.springframework.context.ApplicationContext;

import br.com.vivo.core.controller.impl.utils.ApplicationContextUtils;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

@WebFilter(urlPatterns = { "/*" })
public class HeadBodyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        ApplicationContext applicationContext = ApplicationContextUtils.getApplicationContext();

        ObjectMapper objectMapper = (ObjectMapper) applicationContext.getBean("jacksonObjectMapper");
        JsonFactory jsonFactory = objectMapper.getFactory();

        ByteResponseWrapper byteResponseWrapper = new ByteResponseWrapper((HttpServletResponse) response);
        ByteRequestWrapper byteRequestWrapper = new ByteRequestWrapper((HttpServletRequest) request);


        String jsonRequestString = new String(byteRequestWrapper.getBytes());
        JsonParser requestParser = jsonFactory.createParser(jsonRequestString);
        JsonNode rootRequestNode = objectMapper.readTree(requestParser);


        if(rootRequestNode != null && rootRequestNode.has("body")) {
            JsonNode requestBody = rootRequestNode.get("body");
            writeJsonIntoRequest(byteRequestWrapper, requestBody, objectMapper);
        }


        chain.doFilter(byteRequestWrapper, byteResponseWrapper);

        String jsonResponseString = new String(byteResponseWrapper.getBytes(), response.getCharacterEncoding());



        JsonParser responseParser = jsonFactory.createParser(jsonResponseString);
        JsonNode rootResponseNode = objectMapper.readTree(responseParser);

        Object head = "Whoo hoo!";

        ObjectNode responseObjectWrapper = objectMapper.createObjectNode();
        responseObjectWrapper.put("head", objectMapper.valueToTree(head));
        responseObjectWrapper.put("body", rootResponseNode);

        writeJsonIntoResponse(response, responseObjectWrapper, objectMapper);

    }


    private void writeJsonIntoRequest(ByteRequestWrapper request,
            JsonNode requestBody, ObjectMapper objectMapper) throws IOException {

        String json = objectMapper.writeValueAsString(requestBody);
        request.replaceRequestPayload(json.getBytes());

    }

    @Override
    public void destroy() {

    }



    /**
     * Escreve o json no response
     * 
     * @param response
     * @param rootNode
     * @throws IOException
     */
    private void writeJsonIntoResponse(final ServletResponse response, final JsonNode responseBody, final ObjectMapper objectMapper) throws IOException {

        String json = objectMapper.writeValueAsString(responseBody);

        // escreve o json
        response.getOutputStream().write((json + "\r\n").getBytes(response.getCharacterEncoding()));
    }



    static class ByteResponseWrapper extends HttpServletResponseWrapper {

        private PrintWriter writer;
        private ByteOutputStream output;

        public byte[] getBytes() {
            writer.flush();
            return output.getBytes();
        }

        public ByteResponseWrapper(HttpServletResponse response) {
            super(response);
            output = new ByteOutputStream();
            writer = new PrintWriter(output);
        }

        @Override
        public PrintWriter getWriter() {
            return writer;
        }

        @Override
        public ServletOutputStream getOutputStream() throws IOException {
            return output;
        }
    }



    static class ByteRequestWrapper extends HttpServletRequestWrapper {

        byte[] requestBytes = null;
        private ByteInputStream byteInputStream;


        public ByteRequestWrapper(HttpServletRequest request) throws IOException {
            super(request);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            InputStream inputStream = request.getInputStream();

            byte[] buffer = new byte[4096];
            int read = 0;
            while ( (read = inputStream.read(buffer)) != -1 ) {
                baos.write(buffer, 0, read);
            }

            replaceRequestPayload(baos.toByteArray());
        }

        public byte[] getBytes() {
            return requestBytes;
        }

        @Override
        public BufferedReader getReader() throws IOException {
            return new BufferedReader(new InputStreamReader(getInputStream()));
        }

        @Override
        public ServletInputStream getInputStream() throws IOException {
            return byteInputStream;
        }

        public void replaceRequestPayload(byte[] newPayload) {
            requestBytes = newPayload;
            byteInputStream = new ByteInputStream(new ByteArrayInputStream(requestBytes));
        }
    }

    static class ByteOutputStream extends ServletOutputStream {

        private ByteArrayOutputStream bos = new ByteArrayOutputStream();

        @Override
        public void write(int b) throws IOException {
            bos.write(b);
        }

        public byte[] getBytes() {
            return bos.toByteArray();
        }
    }

    static class ByteInputStream extends ServletInputStream {

        private InputStream inputStream;

        public ByteInputStream(final InputStream inputStream) {
            this.inputStream = inputStream;
        }

        @Override
        public int read() throws IOException {
            return inputStream.read();
        }

    }

}
缪远
2023-03-14

正如Pavel Horal已经提到的,当调用postHandle()方法时,响应体对象已经转换为JSON并写入响应。您可以尝试编写自己的自定义注释和方面,以便拦截控制器响应主体对象。

// custom annotation
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation {
}

// aspect
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MyCustomAnnotationAspect {
    @Around(value = "@annotation(org.package.MyCustomAnnotation)", argNames = "pjp")
    public Object aroundAdvice(final ProceedingJoinPoint pjp) {
        // this is your response body
        Object responseBody = pjp.proceed();
        return responseBody;
    }
}

使用@EnableAEPJAutoProxy启用对AEPUJ方面的支持

 类似资料:
  • 我有一个带有conroller的Spring MVC web应用程序,如下所示: 在这一点上,一切都很好。我要做的是在列表转换为JSON之前,在控制器返回列表的地方拦截请求,并返回包含列表和搜索参数的映射。 现在,由于“不可变”控制器users ResponseBody,控制转到JacksonMessageConverter amd,响应从那里发出。我已经尝试了以下路径,但它们不起作用。 > 拦截

  • 拦截驱动器 bp GetDriveTypeA 获取磁盘驱动器类型 bp GetLogicalDrives 获取逻辑驱动器符号 bp GetLogicalDriveStringsA 获取当前所有逻辑驱动器的根驱动器路径

  • easyopen在1.3.1版本开始支持拦截器。 easyopen拦截器实现原理跟springmvc拦截器类似,拦截器作用在api方法上,即有@Api注解的方法。 拦截器定义如下: /** * 拦截器,原理同springmvc拦截器 * @author tanghc * */ public interface ApiInterceptor { /** * 预处理回调方法,

  • 你可以配置处理器拦截器HandlerInterceptors或web请求拦截器WebRequestInterceptors等拦截器,并配置它们拦截所有进入容器的请求,或限定到符合特定模式的URL路径。 在MVC Java编程配置下注册拦截器的方法: @Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigure

  • Uragano里可以自定义拦截器,并且拦截器分服务器端拦截器和客户端拦截器 拦截器还分全局拦截器和局部拦截器,并且拦截器也是支持依赖注入的 创建拦截器 public class ClientGlobalInterceptor : InterceptorAbstract { private ILogger Logger { get; } public

  • 拦截文件 bp CreateFileA 创建或打开文件 (32位) bp OpenFile 打开文件 (32位) bp ReadFile 读文件 (32位) bp WriteFile 写文件 (32位) bp GetPrivateProfileStringA (ini文件)