spring aop 獲取request、response對象

在網上看到有很多人說以下方式獲取:java

1.在web.xml中添加監聽web

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

2.在aop類中有如下兩種方式獲取session

@Autowired  
HttpServletRequest request; //這裏能夠獲取到request
app

或者ide

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

 

可是我試後,發現都獲取不到。spa

既然這樣那就要用其餘方式獲取了。code

1. 新建一個存儲request、response對象的類xml

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();

相關文章
相關標籤/搜索