HttpServletRequest:Get Session

简介: 接口HttpServletRequest继承自ServletRequest。

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

参考链接

搜狗百科 - httpservletrequest

GNU-javadoc-HttpServletRequest


目录
相关文章
|
6月前
|
存储 应用服务中间件
ServletContext、request、response
ServletContext、request、response
|
应用服务中间件 容器
【JavaWeb】知识总结Ⅹ(HttpServletRequest, HttpServletResponse)
请求行信息:可以使用getMethod()方法获取请求方法(如GET、POST等),使用getRequestURI()方法获取请求的URI(统一资源标识符),使用getProtocol()方法获取请求使用的协议(如HTTP/1.1)。 请求头信息:可以使用getHeader(String name)方法获取指定名称的请求头的值,使用getHeaderNames()方法获取所有请求头的名称的枚举。 请求参数:可以使用getParameter(String name)方法获取指定名称的请求参数的值,使用getParameterNames()方法获取所有请求参数的名称的枚举。
|
Java
如何修改HttpServletRequest的Headers?
HttpServletRequest java
3161 0
|
5月前
|
存储 Java 数据安全/隐私保护
HttpSession详解
HttpSession详解
|
JSON 编解码 前端开发
认识HttpServletRequest和HttpServletResponse
认识HttpServletRequest和HttpServletResponse
|
存储 JavaScript 安全
Cookie和Session在Servlet中的应用
Cookie和Session在Servlet中的应用
|
监控 安全 Java
HttpSession 的 invalidate() 方法介绍
HttpSession 的 invalidate() 方法介绍
421 0
|
XML 缓存 Java
HttpServletRequest 对象
HttpServletRequest对象代表客户端的请求,当客户端通过HTTP协议访问服务器时,HTTP请求头中的所有信息都封装在这个对象中,通过这个对象提供的方法,可以获得客户端请求的所有信息。 其他的具体方法就不详细描述了,具体方法上的使用看API,或者网上查查,有很多的。这里就介绍一下 请求方式 和 获取参数 的问题
|
前端开发 应用服务中间件 程序员
HttpServletRequest接口
HttpServletRequest接口
148 0
HttpServletRequest接口
|
存储 数据安全/隐私保护
HttpServletRequest:增删改查cookie
HttpServletRequest:增删改查cooki
733 0
HttpServletRequest:增删改查cookie