`

request.getSession(false)和request.getSession(true)区别

 
阅读更多
request.getSession(false)和request.getSession(true)区别

以下代码解释一下request.getSession(false)和request.getSession(true)区别的思路,并不是j2ee源代码

个人觉得服务器中保存session是用map来保存的:
例如定义一个保存所有session的map

public GlobalClass
{
	public static final Map map=new HashMap();
	
}


在HttpServletRequest实现类(其中包括getSession()和getSession(boolean flag)方法)中获得map对象
Map map=GlobalClass.map;//获得map对象

public HttpSession getSession(boolean flag)
{
	//在request.getSession(true)情况下;
	//如果map中不存在requestedSessionId(注:requestedSessionId是HttpServletRequest实现类中的一个属性,保存的是从客户端获取的session Id号)键的话,
	//则创建一个HttpSession对象,并保存在map中
	if(flag==true)
	{
		 //不存在,创建
		 if(map.get(requestedSessionId)==null)
		 {
			 HttpSession session=new HttpSession的实现类();  
			 //map中的键是session.getSessionId()值
			 map.put(String.valueOf(session.getSessionId()),session);
			 return session;
		 }

		 //存在
		 else
		 {
			 //requestedSessionId是HttpServletRequest实现类中的一个属性
			 HttpSession tempSession=(HttpSession)map.get(requestedSessionId);
			 //获得map中的session,这个时候要判断session有没有过期;
			 if(过期)
			 {
				//将session中的attribute属性的值设为空
				tempSession.setAttribute(null);
				return tempSession;
			 }
			 else
			 {
				return tempSession;	
			 }
		 }	
	}
	
	//在request.getSession(false)情况下;
	//如果map中不存在requestedSessionId键的话,则返回null,不创建
	else
	{
		//不存在,返回null
		 if(map.get(requestedSessionId)==null)
		 {
			 return null;
		 }
		 //存在
		 else
		 {
			 //requestedSessionId是HttpServletRequest实现类中的一个属性
			 HttpSession tempSession=(HttpSession)map.get(requestedSessionId);
			 //获得map中的session,这个时候要判断session有没有过期;
			 if(过期)
			 {
				//将session中的attribute属性的值设为空
				tempSession.setAttribute(null);
				return tempSession;
			 }
			 else
			 {
				return tempSession;	
			 }
			 
		 }
	}
	 
}

//request.getSession();跟request.getSession(true);是一样的
public HttpSession getSession()
{
	return getSession(true);
}
getSession(boolean create)意思是返回当前reqeust中的HttpSession ,如果当前reqeust中的HttpSession 为null,当create为true,就创建一个新的Session,否则返回null;

简而言之:

HttpServletRequest.getSession(ture) 等同于 HttpServletRequest.getSession() 

HttpServletRequest.getSession(false) 等同于 如果当前Session没有就为null;

【问题和bug】:

我周围很多同事是这样写的;
view plaincopy to clipboardprint?
HttpSession session = request.getSession();   // a new session created if no session exists,如果session不存在的话你又创建了一个!   
String user_name = session.getAttribute("user_name");  
HttpSession session = request.getSession();   // a new session created if no session exists, 如果session不存在的话你又创建了一个!
String user_name = session.getAttribute("user_name2");


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

view plaincopy to clipboardprint?
HttpSession session = request.getSession(false);   
if (session != null) {   
    String user_name = session.getAttribute("user_name");   
}  
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)方法,看看高手写的源码吧:哈哈。。

view plaincopy to clipboardprint?
/**  
 * 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);   
}  
 /**
  * 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 void setSessionAttribute(HttpServletRequest request, String name, Object value)
    {
        Assert.notNull(request, "Request must not be null");
        if(value != null)
        {
            request.getSession().setAttribute(name, value);
        } else
        {
            HttpSession session = request.getSession(false);
            if(session != null)
                session.removeAttribute(name);
        }
    }
注:Assert是Spring工具包中的一个工具,用来判断一些验证操作,本例中用来判断reqeust是否为空,若为空就抛异常。

上面的代码又可以简洁一下啦,看吧:

view plaincopy to clipboardprint?  
String user_name = WebUtils.getSessionAttribute(reqeust, "user_name");

一般在获得一个属性的值时用request.getSession(false),设置值时用request.getSession()
分享到:
评论

相关推荐

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

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

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

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

    数据库测试test.sql

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

    前台页面敏感数据传输到后台钱的加密处理(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); } }

    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"); ...

    java拦截器

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

    实践考核类课二 选课系统

    HttpSession session=request.getSession(true); String stuid=(String) session.getAttribute("usr"); String[] list=request.getParameterValues("chooselist"); for(int count=0;count&lt;list.length;count++){...

    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...

    [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分页处理

    Page page = new Page(request.getParameter("pagetype"),(PaginationBean)request.getSession().getAttribute("page3")); //非第一次进入显示页面 if(!page.isEmpty()){ request.setAttribute("page",...

    canoe-server:游戏服务器框架

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

    word源码java-plugin:一个小苗,希望可以长成参天大树

    word源码java plugin 1.公共组件 plugin-common 该工程主要是搭建web工程需要的一些基本工具和模型,当然这些工具和模型只是在我的体系...request.getSession(true); session.setAttribute(CommonConstant.LOGIN_VALIDA

    jsp 验证码 控件

    HttpSession session=request.getSession(true); response.setContentType("image/jpeg"); response.addHeader("pragma", "NO-cache"); response.addHeader("Cache-Control", "no-cache"); response....

    .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(); // 旋转...

    基于SpringMVC annotation 的图形验证码

    基于SpringMVC annotation ... HttpSession session = request.getSession(true); session.setAttribute("randCheckCode", sRand); g.dispose(); ImageIO.write(image, "JPEG", response.getOutputStream()); } }

    java 面试题 总结

    并说出SessionBean和EntityBean的区别,StatefulBean和StatelessBean的区别。 EJB包括Session Bean、Entity Bean、Message Driven Bean,基于JNDI、RMI、JAT等技术实现。 SessionBean在J2EE应用程序中被用来完成...

    千方百计笔试题大全

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

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

    并说出SessionBean和EntityBean的区别,StatefulBean和StatelessBean的区别。 EJB包括Session Bean、Entity Bean、Message Driven Bean,基于JNDI、RMI、JAT等技术实现。 SessionBean在J2EE应用程序中被用来完成...

    java面试宝典

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

    springmybatis

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

Global site tag (gtag.js) - Google Analytics