1. HttpServletRequest.getSession
1.1 HttpServletRequest
接口HttpServletRequest继承自ServletRequest。
HttpServletRequest extends the javax.servlet.ServletRequest interface to provide request information for HTTP servlets.—— From javadoc
客户端浏览器发出的请求,会被封装成为一个HttpServletRequest对象。
请求的所有的信息,包括请求的地址、请求的参数、提交的数据、上传的文件、客户端的ip,甚至客户端操作系统都包含在其内。
servlet容器会创建一个HttpServletRequest对象,并将其转换为servlet的service、doGet、 doPost等方法的参数。
The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet's service methods (doGet, doPost, etc).—— From javadoc
与Request相对的,HttpServletResponse继承了ServletResponse接口,并提供了与Http协议有关的方法,这些方法的主要功能是设置HTTP状态码和管理Cookie等。
1.2 getSession
HttpServletRequest 提供了两个重载的getSession方法,分别是getSession()和getSession(boolean create)。
getSession()和getSession(true)是相同的,都是获取当前客户端的Session,如果获取不到则创建一个新的Session返回。
getSession(false),也是获取当前客户端的Session,不同的是,如果获取不到则返回null。
getSession
HttpSession getSession()
Gets the HttpSession connected with the client sending the request. If the client didn't have a session connected with him then a new HttpSession will be created. To maintain a session this method must be called before the connection is flushed or closed. Same as calling getSession(true).
Returns:
The HttpSession connected with the client sending the request.
Since:2.1getSession
HttpSession getSession(boolean create)
Gets the HttpSession connected with the client sending the request. If the client didn't have a session connected with him, and create is true then a new HttpSession will be created. If create is false then null is returned. To maintain a session this method must be called before the connection is flushed or closed.
Returns:
The HttpSession connected with the client sending the request.
Since:2.0
—— From javadoc
1.3 getSession() VS. getSession(boolean create)
在大多数场景下,getSession方法的目的是获取当前请求客户端的Session,然后设置或者获取属性。
如果获取不到当前请求客户端的Session,那么重新创建一个Session,一般情况下意义不大,纯属浪费。
因此推荐使用getSession(false)的方式来获取Session,注意先判空再使用即可,下面会详细介绍。
2. springmvc-session.xml
2.1 SessionUtil
通常从Session里存取属性的代码如下:
HttpSession session=request.getSession(false); session.setAttribute("bar", new Long("1024")); Object foo=session.getAttribute("foo");
可以抽取为工具类SessionUtil:
public final class SessionUtil{ public static void setAttribute(HttpServletRequest request,String attributeName,Serializable attributeValue){ request.getSession().setAttribute(attributeName, attributeValue); } public static <T> T getAttribute(HttpServletRequest request,String attributeName){ Validate.notNull(request, "request can't be null!"); HttpSession session = request.getSession(false); return session == null ? null : (T) session.getAttribute(attributeName); } }
2.2 SessionAccessor
为了便于统一管理Session,可以将存取Session属性统一配置在XML中,实现和使用方式如下。
- SessionUtil
import java.io.Serializable; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; public final class SessionUtil{ public static <T> T getAttribute(HttpServletRequest request,String attributeName){ HttpSession session = request.getSession(false); return session == null ? null : (T) session.getAttribute(attributeName); } public static void setAttribute(HttpServletRequest request,String attributeName,Serializable attributeValue){ request.getSession().setAttribute(attributeName, attributeValue); } public static void removeAttribute(HttpServletRequest request,String attributeName){ HttpSession session = request.getSession(false); if (null == session){ return; } session.removeAttribute(attributeName); } /** * 遍历session的attribute,将 name /attributeValue 存入到map里. */ public static Map<String, Serializable> getAttributeMap(HttpSession session){ Map<String, Serializable> map = new HashMap<String, Serializable>(); Enumeration<String> attributeNames = session.getAttributeNames(); while (attributeNames.hasMoreElements()){ String name = attributeNames.nextElement(); map.put(name, (Serializable) session.getAttribute(name)); } return map; } private SessionUtil(){ throw new AssertionError("can not creat " + getClass().getName() + " instance"); } }
- Accessible
import java.io.Serializable; import javax.servlet.http.HttpServletRequest; public interface Accessible{ public void save(String key,Serializable serializable,HttpServletRequest request); public <T extends Serializable> T get(String key,HttpServletRequest request); public void remove(String key,HttpServletRequest request); }
- AbstractSessionAccessor
import java.io.Serializable; import javax.servlet.http.HttpServletRequest; import com.feilong.servlet.http.SessionUtil; public class AbstractSessionAccessor implements Accessible{ @Override public void save(String key,Serializable serializable,HttpServletRequest request){ SessionUtil.setAttribute(request, key, serializable); } @Override public <T extends Serializable> T get(String key,HttpServletRequest request){ return SessionUtil.getAttribute(request, key); } @Override public void remove(String key,HttpServletRequest request){ SessionUtil.removeAttribute(request, key); } }
- SessionAccessor
package demo.session; import java.io.Serializable; import javax.servlet.http.HttpServletRequest; public class SessionAccessor extends AbstractSessionAccessor{ private String key; public void save(Serializable serializable,HttpServletRequest request){ super.save(key, serializable, request); } public <T extends Serializable> T get(HttpServletRequest request){ return super.get(key, request); } public void remove(HttpServletRequest request){ super.remove(key, request); } public SessionAccessor(){} public SessionAccessor(String key){ this.key = key; } public void setKey(String key){ this.key = key; } public String getKey(){ return key; } }
- springmvc-session.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd "> <bean name="fooSessionAccessor" class="demo.session.SessionAccessor"> <property name="key" value="attr_name_foo" /> </bean> </beans>
- FooController
@Controller public class FooController extends BaseController{ @Autowired @Qualifier("fooSessionAccessor") private SessionAccessor fooSessionAccessor; @ResponseBody @RequestMapping(value = "/root/path/foo",method = RequestMethod.POST) public Object foo(HttpServletRequest request,HttpServletResponse response){ guestKeySessionAccessor.save("value1", request); guestKeySessionAccessor.get(request); guestKeySessionAccessor.remove(request); } }
参考链接
GNU-javadoc-HttpServletRequest