简体   繁体   English

Java:如何从控制器返回后对Filter进行拦截

[英]Java: How to get intercept on Filter after it returns from the controller

I have implemented a Filter like this but this triggers only when the request is coming in. I would like to intercept the response on its way out ie when the response is returned from controller. 我已经实现了像这样的过滤器,但只有在请求进入时才触发。我想在出路时拦截响应,即从控制器返回响应时。

I know about Spring Interceptors which give you the functionality to handle the request before and after it hits the controller. 我知道Spring Interceptor会给你在触及控制器之前和之后处理请求的功能。 I would like to do something like that. 我想做那样的事情。

public class ServiceSessionManagementInterceptor implements Filter{

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    // TODO Auto-generated method stub

}

@Override
public void doFilter(ServletRequest request, ServletResponse response,  FilterChain chain) throws IOException, ServletException {
    // TODO Auto-generated method stub
    Map<String, String[]> maps = request.getParameterMap();

    System.out.println("test");
chain.doFilter(request, response);  
}

@Override
public void destroy() {
    // TODO Auto-generated method stub

}

} }

The doFilter() is where magic happens. doFilter()是魔术发生的地方。 Whatever you put before it will be executed before the servlet and everything you put after it will be executed after the servlet service() method returns (including a forward/include, etc.). 无论你在它之前执行什么,它都将在servlet之前执行,你在它之后放的所有内容都将在servlet service()方法返回后执行(包括forward / include等)。

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

    System.out.println("before");
    chain.doFilter(request, response);  
    System.out.println("after");
}

This way you could wrap the ServletRequest and ServletResponse objects with your own implementations to add functionality, ex: compression. 这样您就可以使用自己的实现来包装ServletRequestServletResponse对象以添加功能,例如:压缩。

Note that a Spring Interceptor is called before and after the handler method gets executed. 请注意,在执行处理程序方法之前和之后调用Spring Interceptor A servlet Filter gets executed before and after a Servlet . Servlet FilterServlet之前和之后执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM