封装request,response使之可以全局访问

1. 封装request,response为RequestContext

服务器收到一个http请求,会对每个请求创建一个HttpServletRequest和HttpServletResponse,HttpServletRequest封装请求信息,HttpServletResponse封装响应信息。
每个请求都是独立的线程,这里我们使用ThreadLocal来保存request,和response,ThreadLocal会使每个线程数据相互隔离。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class RequestContext{
private static final Logger logger = LoggerFactory.getLogger(RequestContext.class);

private static ThreadLocal<HttpServletRequest> requestContext = new ThreadLocal<HttpServletRequest>();
private static ThreadLocal<HttpServletResponse> responseContext = new ThreadLocal<HttpServletResponse>();

public static void init(HttpServletRequest request, HttpServletResponse response){
setRequest(request);
setResponse(response);
}

public static HttpSession getSession(){
if (getRequest() == null){
return null;
}
return getRequest().getSession(true);
}

public static HttpServletRequest getRequest(){
return requestContext.get();
}

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

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

public static void setResponse(HttpServletResponse response){
responseContext.set(response);
}

public static void clear(){
requestContext.remove();
responseContext.remove();
}
}

2. 添加filter管理 RequestContext

将此filter添加到web.xml中,就可以全局使用request和response了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class RequestContextFilter implements Filter {

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

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;

RequestContext.init(request, response);
try {
filterChain.doFilter(request, response);
} finally {
RequestContext.clear();
}
}

@Override
public void destroy() {
}

3. 优点

可以全局使用request和response,减少代码侵入性。

坚持原创技术分享,您的支持将鼓励我继续创作!
显示 Gitment 评论