记得在一篇博文中看到描述threadLocal的一句话:
ThreadLocal除了适用于多线程保证每条线程都有自己的变量副本外,还适用于在线程上下文中共享某些变量值。
这两种说法是有区别的。前者强调的是,使用ThreadLocal对副本做保护,避免同步、加锁,降低效率;后者强调的是,某个变量线程上下文中,A处用到、B处用到、C处用到,先在入口处set一个值,后使用ThreadLocal的get方法直接在需要用到的地方拿这个值。
项目中,最近理由cookie存值,使用到了threadLocal这个字段,自己就想去研究下,原理这里跟后者强调的一样,上代码:
1.web.xml里边配置过滤器,拦截请求,做处理
<filter> <filter-name>InterceptorFilter</filter-name> <filter-class>com.fx.anniversary.core.filter.InterceptorFilter</filter-class> </filter> <filter-mapping> <filter-name>InterceptorFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2.赋值
public class InterceptorFilter implements Filter{ publicvoiddestroy(){ } publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain)throwsIOException,ServletException{ HttpServletRequesthttpRequest=(HttpServletRequest)request; HttpServletResponsehttpResponse=(HttpServletResponse)response; InterceptorContext.setRequest(httpRequest); InterceptorContext.setResponse(httpResponse); try{ chain.doFilter(request, response); }finally{ //不管有木有出现异常,finally块中代码都会执行;在这里,相当于只服务于当前请求。 InterceptorContext.removeRequest(); InterceptorContext.removeResponse(); } } public void init(FilterConfigfilterConfig)throwsServletException{ } }
3.InterceptorContext实体
public class InterceptorContext{ private static ThreadLocal<httpservletrequest> _request = newThreadLocal<httpservletrequest>(); private static ThreadLocal<httpservletresponse> _response = newThreadLocal<httpservletresponse>(); publicstaticvoidsetRequest(HttpServletRequestrequest){ _request.set(request); } public static HttpServletRequestgetRequest(){ HttpServletRequestrequest=_request.get();returnrequest; } public static void removeRequest(){ _request.remove(); } public static void setResponse(HttpServletResponseresponse){ _response.set(response); } public static HttpServletResponsegetResponse(){ HttpServletResponseresponse=_response.get(); return response; } public static void removeResponse(){ _response.remove(); } }
4.项目中的开始调用。(因为这两个方法调用的地方太多,每次都带一个参数也比较繁琐,所以采用这种方式,文章开头总结过)
public String getAttribute(Stringkey){ HttpServletRequestrequest = InterceptorContext.getRequest(); Cookie[]cookies=request.getCookies(); if(cookies!=null){ for(Cookie cookie: cookies){ if(cookie.getName().equals(key)){ return cookie.getValue(); } } } return""; } @Override public void setAttribute(String key,String value){ HttpServletResponse response=InterceptorContext.getResponse(); Cookiecookie=newCookie(key,value); response.addCookie(cookie); }
补充知识:利用ThreadLocal管理request和session以及用户信息,实现 Use anywhere
1.我们有时需要获取request或session中的数据的时候,首先需要获取request和session对象,这个通常是在Controller的时候当做入参获取,这样方法的入参会显得很长很臃肿的感觉。这就是的出发点,接下来就展示一下是如何实现的。
2.首先我们写个一个拦截器:WebContextFilter
package com.office.common.filter; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.filter.OncePerRequestFilter; import com.office.common.context.WebContextHolder; /** * webcontent信息加载到TheadLocal中 * @author Neo * @date 2017年10月20日11:38:45 */ public class WebContextFilter extends OncePerRequestFilter { public WebContextFilter() { } protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (request == null || response == null) { return; } else { WebContextHolder.setRequest(request); WebContextHolder.setResponse(response); filterChain.doFilter(request, response); return; } } }
3.然后我们将写好的拦截器配置到web.xml中:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>Archetype Created Web Application</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value></param-value> </context-param> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- ******************************************************************* --> <!-- *************** webcontent信息加载到TheadLocal中 ******************** --> <!-- ******************************************************************* --> <filter> <filter-name>webContentFilter</filter-name> <filter-class>com.office.common.filter.WebContextFilter</filter-class> </filter> <filter-mapping> <filter-name>webContentFilter</filter-name> <url-pattern>/*</url-pattern><!-- /* --> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
4.编写一个同一个管理操作工具类:WebContextHolder
package com.office.common.context; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.office.common.dto.UserDTO; /** * 上下文 * @author Neo * @date 2017年10月20日11:42:57 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class WebContextHolder { public WebContextHolder() { } public static String getRequestIp() { if (getRequest() == null) return null; HttpServletRequest request = getRequest(); String ip = request.getHeader("X-Forwarded-For"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) ip = request.getHeader("Proxy-Client-IP"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) ip = request.getHeader("WL-Proxy-Client-IP"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) ip = request.getHeader("HTTP_CLIENT_IP"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) ip = request.getHeader("HTTP_X_FORWARDED_FOR"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) ip = request.getRemoteAddr(); } else if (ip.length() > 15) { String ips[] = ip.split(","); int index = 0; do { if (index >= ips.length) break; String strIp = ips[index]; if (!"unknown".equalsIgnoreCase(strIp)) { ip = strIp; break; } index++; } while (true); } return ip; } public static HttpServletRequest getRequest() { if (requestLocal == null) return null; else return (HttpServletRequest) requestLocal.get(); } public static String getContextPath() { if (getRequest() == null) return null; else return (new StringBuilder()).append(getRequest().getContextPath()).append("/").toString(); } public static String getCurrRequestURI() { if (getRequest() == null) return null; else return (new StringBuilder()).append(getRequest().getRequestURI().replace(getRequest().getContextPath(), "")) .append("/").toString(); } public static HttpServletResponse getResponse() { if (responseLocal == null) return null; else return (HttpServletResponse) responseLocal.get(); } public static HttpSession getSession() { if (requestLocal == null) return null; if (requestLocal.get() == null) return null; else return ((HttpServletRequest) requestLocal.get()).getSession(); } public static UserDTO getLoginUserSession(Class loginUserClass) { if (getSession() == null) return null; Object obj = getSession().getAttribute(CURRENT_USER); if (obj == null) return null; else return (UserDTO) obj; } public static UserDTO getLoginUserSession() { return getLoginUserSession(UserDTO.class); } public static void createLoginUserSession(UserDTO loginUser) { if (loginUser != null) getSession().setAttribute(CURRENT_USER, loginUser); } public static void destroyLoginUserSession() { if (getLoginUserSession() != null) { getSession().removeAttribute(CURRENT_USER); getSession().invalidate(); } } public static void setRequest(HttpServletRequest request) { if (requestLocal == null) requestLocal = new ThreadLocal(); requestLocal.set(request); } public static void setResponse(HttpServletResponse response) { if (responseLocal == null) responseLocal = new ThreadLocal(); responseLocal.set(response); } /** * 获取项目请求的根目录 * * @return eg:http://localhost:8080/projectName */ public static String getProjectRequestRootPath() { HttpServletRequest request = WebContextHolder.getRequest(); StringBuffer sb = new StringBuffer(); sb.append(request.getScheme()). append("://"). append(request.getServerName()). append(":"). append(request.getServerPort()). append(request.getContextPath()). append("/"); return sb.toString(); } private static ThreadLocal requestLocal; private static ThreadLocal responseLocal; public static String CURRENT_USER = "CURRENT_USER"; }
5.使用展示:
//我们可以在任何地方使用这种方法取值
WebContextHolder.getRequest().getParameter("id");
以上这篇关于ThreadLocal对request和response的用法说明就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持小牛知识库。
问题内容: 一旦碰到了一个模式,就将其中和响应对象放入servlet的局部变量。Servlet类还具有获取当前请求和响应对象的方法。因此,为了获得这些对象,您仍然需要使用servlet对象。 这些局部变量的意义何在? 问题答案: 关键是将请求和响应对象放在本来没有类的类中(例如,它们不是servlet)。一个示例是JSF托管Bean- 它们的方法不带参数,因此您可以通过来获取请求,该请求将它们包含
The request and response objects wrap the WSGI environment or the return value from a WSGI application so that it is another WSGI application (wraps a whole application). How they Work Your WSGI appli
本文向大家介绍JSP 中request与response的用法详解,包括了JSP 中request与response的用法详解的使用技巧和注意事项,需要的朋友参考一下 JSP 中request与response的用法详解 概要: 在学习这两个对象之前,我们应该已经有了http协议的基本了解了,如果不清楚http协议的可以看我的关于http协议的介绍。因为其实request和response的使用大
本文向大家介绍小论asp中request与response的用法,包括了小论asp中request与response的用法的使用技巧和注意事项,需要的朋友参考一下 request的用法: request有三种获取表单值的方法,分别用于不同的表单递交方法的获取。表单简单地可以认为是指页面所要传递的参数的一个集合,而其递交的方法有两个post和get。在这两种方法里面,分别对应着不同的接收方法,其具体
本文向大家介绍YII Framework学习之request与response用法(基于CHttpRequest响应),包括了YII Framework学习之request与response用法(基于CHttpRequest响应)的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了YII Framework学习之request与response用法。分享给大家供大家参考,具体如下: YII中提
本文向大家介绍对django views中 request, response的常用操作详解,包括了对django views中 request, response的常用操作详解的使用技巧和注意事项,需要的朋友参考一下 request 获取post请求中的json数据 json格式还有一些 非表单序列化 的格式,都可以从 request.body 中获取请求体中的数据,对于ajax请求可以使用 r