`
frank1998819
  • 浏览: 752058 次
  • 性别: 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)的区别

    本文将深入探讨`request.getSession(true)`、`request.getSession(false)`以及`request.getSession(null)`的区别,并提供最佳实践建议。 首先,让我们了解`getSession()`方法的基本行为。根据Servlet官方文档,`...

    request.getSession().doc

    Request.getSession() 方法详解 Request.getSession() 方法是 HttpServletRequest 对象中的一个方法,用于获取当前 HTTP 请求关联的 HttpSession 对象。如果当前会话不存在,可以通过 create 参数控制是否创建一个...

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

    总之,理解`request.getSession()`和`request.getSession(false)`的区别至关重要,因为它关系到会话的生命周期管理和应用程序的性能。正确使用这些方法,可以避免不必要的资源浪费,并提高程序的健壮性。在编写代码...

    数据库测试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 ...

    SSM项目 拦截器(csdn)————程序.pdf

    HttpSession session = request.getSession(); final Object userObj = session.getAttribute(ProjShow.USER_SESSION); if (userObj != null) { // 如果已经登录,不拦截 return true; } else { // 如果...

    spring_mvc控制网站登录用户失效后跳登录页面

    EkaUserModel ekaUser = (EkaUserModel) request.getSession().getAttribute("ekaUser"); if (ekaUser == null) { logger.log(Level.INFO, "用户未登录"); response.sendRedirect("../login.jsp"); return ...

    于笑扬java综合知识点总结-必背(吐血推荐).doc

    request.getSession()方法用于获取当前会话,request.getSession(false)和request.getSession(true)是它的变体: * request.getSession():获取当前会话,如果不存在则创建一个新的会话 * request.getSession(false...

    解决重复提交、上传组件

    request.getSession().setAttribute(sessionId + "_token", UUID.randomUUID().toString()); return invocation.invoke(); } } ``` 在Action配置中添加这个拦截器: ```xml ...

    SpringMVC拦截器实现登录认证

    HttpSession session = request.getSession(); // 检查用户是否已登录 Object user = session.getAttribute("USER"); if (user == null) { // 如果用户未登录,重定向到登录页面 response.sendRedirect("/...

    mvc的拦截器控制权限的例子

    User user = (User) request.getSession().getAttribute("USER_INFO"); if (user == null) { // 如果未登录,重定向到登录页面 response.sendRedirect("/login"); return false; } // 可以根据URL判断权限...

    session的使用

    另外,还可以直接调用 `request.getSession()` 方法,这等同于调用 `request.getSession(true)`。 ##### 使用 在 `javax.servlet.http.HttpSession` 接口中定义了一系列方法,用于操作会话数据: - `void ...

    企业级开发-SpringMVC使用拦截器实现用户登录权限验证实验报告.docx

    User user = (User) request.getSession().getAttribute("currentUser"); if (user == null) { // 用户未登录,重定向到登录页面 response.sendRedirect("/login"); return false; } return true; } } ``` ...

    于笑扬java综合知识点总结-必背.pdf

    request.getSession() reqeust.getSession(false)和 request.getSession(true) 在 Servlet 中,request.getSession() 方法用于获取当前会话对象。如果没有当前会话对象,request.getSession() 方法将创建一个新的...

    jsp实现登录验证的过滤器.docx

    HttpSession session = req.getSession(true); resp.setContentType("text/html;"); resp.setCharacterEncoding("utf-8"); PrintWriter out = resp.getWriter(); // 获取请求URI和上下文路径,判断是否为登录...

    JavaWeb使用Session和Cookie实现登录认证

    String str = (String) request.getSession().getAttribute("isLogin"); // 如果登录状态不为空则返回 true,返回 true 则会执行相应 controller 的方法 if (str != null) { return true; } // 如果登录状态为...

    解决在struts 中可以通过token 来重复提交的问题

    String tokenFromSession = (String) request.getSession().getAttribute("token"); // 从session获取Token if (tokenFromForm != null && tokenFromForm.equals(tokenFromSession)) { // Token有效,进行后续...

    SpringMVC03.zip

    if (request.getSession().getAttribute("userId") == null) { response.sendRedirect("/login"); // 未登录,重定向到登录页 return false; // 阻止请求继续处理 } return true; // 用户已登录,允许请求继续 ...

    java综合知识

    `request.getSession(false)`如果无现有会话则返回null;`request.getSession(true)`强制创建新会话。 11. **Page和PageContext的区别**:在JSP中,Page代表当前页面对象,而PageContext提供了对JSP上下文的访问,...

Global site tag (gtag.js) - Google Analytics