`

对request.getSession(false)的理解

 
阅读更多
来源:对request.getSession(false)的理解
在网上经常看到有人对request.getSession(false)提出疑问,我第一次也很迷惑,看了一下J2EE API,看一下官网是怎么解释的。
【官方解释】

public HttpSession getSession(boolean create)

  Returns the current HttpSession associated with this request or, if if there is no current session and create is true, returns a new session. If create is false and the request has no valid HttpSession, this method returns null.

  To make sure the session is properly maintained, you must call this method before the response is committed. If the container is using cookies to maintain session integrity and is asked to create a new session when the response is committed, an IllegalStateException is thrown.

Parameters: true - to create a new session for this request if necessary; false to return null if there's no current session
Returns: the HttpSession associated with this request or null if create is false and the request has no valid session
   译:
getSession(boolean create)意思是返回当前reqeust中的HttpSession ,如果当前reqeust中的HttpSession 为null,当create为true,就创建一个新的Session,否则返回null;

简而言之:
HttpServletRequest.getSession(ture) 等同于 HttpServletRequest.getSession()
HttpServletRequest.getSession(false) 等同于 如果当前Session没有就为null;
【问题和bug】:
我周围很多同事是这样写的;

HttpSession session = request.getSession(); // a new session created if no session exists, 哈哈!完蛋啦!如果session不存在的话你又创建了一个!
String user_name = session.getAttribute("user_name");

需要注意的地方是request.getSession() 等同于 request.getSession(true),除非我们确认session一定存在或者sesson不存在时明确有创建session的需要,否则尽量使用request.getSession(false)。在使用request.getSession()函数,通常在action中检查是否有某个变量/标记存放在session中。这个场景中可能出现没有session存在的情况,正常的判断应该是这样:
HttpSession session = request.getSession(false);
if (session != null) {
String user_name = session.getAttribute("user_name");
}


【投机取巧】:
如果项目中用到了Spring(其实只要是Java的稍大的项目,Spring是一个很好的选择),对session的操作就方便多了。如果需要在Session中取值,可以用WebUtils工具(org.springframework.web.util.WebUtils)的getSessionAttribute(HttpServletRequest request, String name)方法,看看高手写的源码吧:哈哈。。
代码如下:
/**
* Check the given request for a session attribute of the given name.
* Returns null if there is no session or if the session has no such attribute.
* Does not create a new session if none has existed before!
* @param request current HTTP request
* @param name the name of the session attribute
* @return the value of the session attribute, or <code>null</code> if not found
*/

public static 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是否为空,若为空就抛异常。
分享到:
评论

相关推荐

    request.getSession().doc

    request.getSession().doc

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

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

    jsp 对request.getSession(false)的理解(附程序员常疏忽的一个漏洞)

    在网上经常看到有人对request.getSession(false)提出疑问,我第一次也很迷惑,看了一下J2EE1.3 API,看一下官网是怎么解释的。

    request.setAttribute 语句前总显示红色感叹号解决办法 HTTP Status 500 -

    description The server encountered an internal error () that prevented it from fulfilling this request. exception javax.servlet.ServletException: Servlet execution threw an exception root cause ...

    基于servlet的购物车

    Map, Book&gt; books = (Map, Book&gt;)request.getSession().getServletContext().getAttribute("books"); Book book = books.get(bookid); System.out.println(book); //得到数量 int bookNum = Integer....

    关于jsp语法和练习

    request.getSession (). GetAttributes() 答案: A 2. JSP页面需要创建仅在本页面使用的JavaBean的示例,为了完成此功能必须使用jsp:useBean的哪两个属性进行设置?(选择两个选项) A. id B. type C. name D. ...

    数据库测试test.sql

    HttpSession session = request.getSession(); // session.setAttribute("username",username); session.setAttribute("user",user); //response.sendRedirect("/myservlet2/admin/success.jsp"); //response....

    request.getParameter()取值为null的解决方法

    在后台通过Request取值为null,是因为只设置了id属性,而取值候用的是name属性,问题就出现在这里

    javaweb 做图片水印,水印图片到目录图片上去

    String planeImage = request.getSession().getServletContext().getRealPath("/image").replace("\\", "/")+"/"+"symark.png"; //获取目标图片的路径String targetPic = request.getSession().getServletContext()....

    用户管理系统(ums)

    HttpSession session= request.getSession(); // 设置session的值 session.setAttribute("userList", list); //跳转到显示的页面,格式(得到当前页面的+要跳转的页面) response.sendRedirect(request....

    weChatpay完整版java

    UserAccessToken token = (UserAccessToken) request.getSession().getAttribute("UserAccessToken"); if(null==token){ token = util.getAccessToken3(Constants.APPID, Constants.SECRET,code); ...

    图片上传并回显插件11111

    .getSession().getServletContext()); MultipartHttpServletRequest multipartRequest = resolver .resolveMultipart(request); MultipartFile file = multipartRequest.getFile("fileList"); 这个file就能...

    Java类写的随机验证码

    1、在JSP页面中用标记应用验证码。 ...HttpSession session = request.getSession(); String rancode = (String)session.getAttribute("random"); if(code.equals(rancode)){//判断用户输入的对否

    前台页面敏感数据传输到后台钱的加密处理(md5加密)

    js:(jsp页面引入md5.js文件) var mobile=$("input[name='mobile']").val(); var hash1=hex_md5(mobile); $("input[name='hidmobile']").val... request.getSession().setAttribute("actList", actList); } }

    java小项目

    HttpSession session = request.getSession(); session.setAttribute("userName", name); session.setAttribute("pwd", pwd); session.setAttribute("msgList", msgList); response.sendRedirect("jspPages/...

    购物网站系统

    HttpSession session = request.getSession(false); String cusername=(String) session.getAttribute("cusername"); ContentInfobiz contentInfobiz=new ContentInfobiz(); int c=contentInfobiz.addcont(c...

    登录过滤器

    HttpSession session = request.getSession(); //是否登录 //开放注册页面 if(null==session.getAttribute("merchantInfo") &&request.getRequestURL().indexOf("regist/merchant/acount.jsp")==-1){ ...

    jsp源码-网络交易系统

    List&lt;Article&gt; alist1 = (List)request.getSession().getAttribute("alist1"); Iterator&lt;Article&gt; in1 = alist1.iterator(); List&lt;Article&gt; alist2 = (List)request.getSession().getAttribute("alist2"); ...

    session、cookie的跨域共享

    同时你可以通过ie、firefox去测试你对session、cookie的理解在此之前是否正确,可以简单告诉你session不是我们大都认为的在登录时候,通过request.getSession()产生的,而是你在首次访问一个应用时候,就已经产生了...

Global site tag (gtag.js) - Google Analytics