spring aop 获取request、response对象详解编程语言

在网上看到有不少人说如下方式获取:

1.在web.xml中添加监听

<listener>  
        <listener-class>  
            org.springframework.web.context.request.RequestContextListener  
        </listener-class>  
</listener>

2.在aop类中有以下两种方式获取

@Autowired  
HttpServletRequest request; //这里可以获取到request

或者

HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

 

但是我试后,发现都获取不到。

既然这样那就要用其他方式获取了。

1. 新建一个存储request、response对象的类

import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import javax.servlet.http.HttpSession; 
 
public class SysContent { 
    private static ThreadLocal<HttpServletRequest> requestLocal = new ThreadLocal<HttpServletRequest>(); 
    private static ThreadLocal<HttpServletResponse> responseLocal = new ThreadLocal<HttpServletResponse>(); 
 
    public static HttpServletRequest getRequest() { 
        return (HttpServletRequest) requestLocal.get(); 
    } 

    public static void setRequest(HttpServletRequest request) {
        requestLocal.set(request);
    }

    public static HttpServletResponse getResponse() {
        return (HttpServletResponse) responseLocal.get();
    }

    public static void setResponse(HttpServletResponse response) {
        responseLocal.set(response);
    }
public static HttpSession getSession() { return (HttpSession) ((HttpServletRequest) requestLocal.get()).getSession(); } }

2. 新建一个filter,并在web.xml中添加filter配置

import java.io.IOException; 
 
import javax.servlet.Filter; 
import javax.servlet.FilterChain; 
import javax.servlet.FilterConfig; 
import javax.servlet.ServletException; 
import javax.servlet.ServletRequest; 
import javax.servlet.ServletResponse; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
 
public class InitContent implements Filter { 
 
    @Override 
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) 
            throws IOException, ServletException { 
        SysContent.setRequest((HttpServletRequest) arg0); 
        SysContent.setResponse((HttpServletResponse) arg1); 
        arg2.doFilter(arg0, arg1); 
    } 
 
    @Override 
    public void init(FilterConfig arg0) throws ServletException { 
    } 
    @Override 
    public void destroy() { 
    } 
 
}

web.xml

    <filter> 
        <filter-name>InitContent</filter-name> 
        <filter-class>com.*.filter.InitContent</filter-class> 
    </filter> 
    <filter-mapping> 
        <filter-name>InitContent</filter-name> 
        <url-pattern>/*</url-pattern> 
    </filter-mapping>

 

这样一来,每次请求的request、response都存在了ThreadLocal中,每次需要的时候从里面获取即可

HttpServletRequest request = SysContent.getRequest();
HttpServletResponse response = SysContent.getResponse();
HttpSession session = SysContent.getSession();

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/14019.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论