`
frank1998819
  • 浏览: 731099 次
  • 性别: Icon_minigender_1
  • 来自: 南京
文章分类
社区版块
存档分类

关于request.getSession(true/false/null)的区别 (转)

 
阅读更多
关于request.getSession(true/false/null)的区别一、需求原因

现实中我们经常会遇到以下3中用法:

HttpSession session = request.getSession();

HttpSession session = request.getSession(true);

HttpSession session = request.getSession(false);

二、区别

1.      Servlet官方文档说:
public HttpSessiongetSession(boolean create)
Returns the currentHttpSession associated with this request or, if if there is no current sessionand create is true, returns a new session.
If create is falseand the request has no validHttpSession, this method returns null.
To make sure thesession is properly maintained, you must call this method before the responseis committed. If the container is using cookies to maintain session integrityand is asked to create a new session when the response is committed, anIllegalStateException is thrown.
Parameters: true -to create a new session for this request if necessary; false to return null ifthere's no current session
Returns: theHttpSession associated with this request or null if create is false and therequest has no valid session

2.      翻译过来的意思是:

getSession(boolean create)意思是返回当前reqeust中的HttpSession ,如果当前reqeust中的HttpSession 为null,当create为true,就创建一个新的Session,否则返回null;
简而言之:
HttpServletRequest.getSession(ture)等同于 HttpServletRequest.getSession()
HttpServletRequest.getSession(false)等同于 如果当前Session没有就为null;

3.      使用

当向Session中存取登录信息时,一般建议:HttpSession session =request.getSession();

当从Session中获取登录信息时,一般建议:HttpSession session =request.getSession(false);

4.      更简洁的方式

如果你的项目中使用到了Spring(当然大点的项目都用到了),对session的操作就方便多了。如果需要在Session中取值,可以用WebUtils工具(org.springframework.web.util.WebUtils)的getSessionAttribute(HttpServletRequestrequest, String name)方法,看看源码:

publicstatic Object getSessionAttribute(HttpServletRequest request, String name){  

Assert.notNull(request, "Request must not be null");  

HttpSession session =request.getSession(false);  

return (session != null ?session.getAttribute(name) : null);  

}

注:Assert是Spring工具包中的一个工具,用来判断一些验证操作,本例中用来判断reqeust是否为空,若为空就抛异常

你使用时:WebUtils.setSessionAttribute(request, “user”, User);

        User user = (User)WebUtils.getSessionAttribute(request, “user”);

三、运行结果

以上例子均测试验证通过。

http://www.linuxso.com/architecture/20470.html
分享到:
评论

相关推荐

    java 中 request.getSession(true、false、null)的区别

    主要介绍了java 中 request.getSession(true/false/null)的区别的相关资料,需要的朋友可以参考下

    数据库测试test.sql

    ... ... ... import javax.servlet.RequestDispatcher;...import javax.servlet.ServletContext;... response.sendRedirect("../admin/success.jsp"); }else{ //失败跳转回登录页面 //out.println("登录失败"); ...

    java拦截器

    User user = (User) request.getSession().getAttribute("user"); try { if (user.equals(null)) { response.sendRedirect(serverConfig.SERVER + "admin/user/goLogin"); return false; } else { return ...

    [C#]统计在线人数

    dt.Columns["SessionID"].Unique = true; dt.PrimaryKey = new DataColumn[]{dt.Columns["SessionID"]}; System.Web.HttpContext.Current.Application["OnlineTalbe"] = dt; System.Web.HttpContext.Current....

    Java Oracle分页处理

    <form action="./list.do" method="get">跳到第 <select name ="pagetype" onchange="document.forms[0].submit()"> for(i=1;i${page.totalPages};i++) document.write(...

    .jsp和servlet验证码

    request.getSession(true).setAttribute("codes", vcode); for (int i = 0; i ; i++) { g2.setFont(new Font("Times New Roman", Font.HANGING_BASELINE, FontSize)); double rot = getRandomJiao(); // 旋转...

    servlet2.4doc

    The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. doGet...

    springmybatis

    public static SqlSessionFactory getSession(){ return sqlSessionFactory; } public static void main(String[] args) { SqlSession session = sqlSessionFactory.openSession(); try { User user = ...

    canoe-server:游戏服务器框架

    Session session = request.getSession(); session.setRole(null); } 事件管理机制,并且包含标注方式的事件侦听,该机制在我们自己项目里的解耦业务逻辑与通讯逻辑起到与上一条同等重要的作用。 @Ev

    千方百计笔试题大全

    106、HttpSession session = request.getSession() 24 107、getParameter与 getAttribute的区别? 24 108、以下哪一个不是赋值符号? 25 109、以下哪个不是Collection的子接口? 25 110、.BufferedReader的父类是以下...

    java 面试题 总结

    HashMap是Hashtable的轻量级实现(非线程安全的实现),他们都完成了Map接口,主要区别在于HashMap允许空(null)键值(key),由于非线程安全,效率上可能高于Hashtable。 HashMap允许将null作为一个entry的key或者...

    java面试宝典

    106、HttpSession session = request.getSession() 24 107、getParameter与 getAttribute的区别? 24 108、以下哪一个不是赋值符号? 25 109、以下哪个不是Collection的子接口? 25 110、.BufferedReader的父类是以下...

    超级有影响力霸气的Java面试题大全文档

    HashMap是Hashtable的轻量级实现(非线程安全的实现),他们都完成了Map接口,主要区别在于HashMap允许空(null)键值(key),由于非线程安全,效率上可能高于Hashtable。 HashMap允许将null作为一个entry的key或者...

    jsp内置对象的用法

    13 public Object findAttribute(String name) 寻找一属性,返回起属性值或NULL 14 void removeAttribute(String name) 删除某属性 15 void removeAttribute(String name,int scope) 在指定范围删除某属性 16 ...

Global site tag (gtag.js) - Google Analytics