`
serisboy
  • 浏览: 170292 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

创建session学习-request.getSession()

阅读更多
在HttpServlet中,HttpSession对象通常在request.getSession(true)方法调用时才创建。 HttpSession的使用是有代价的,需要占用服务器资源,本着能不浪费就不浪费的原则,我希望系统中的session都在掌握之中,在需要创建时由我们的代码明确创建。但是最近在开发中发现,新的session对象经常在意料之外出现,究竟是谁在创建session呢?

最常见的地方是错误的使用request.getSession()函数,通常在action中检查是否有某个变量/标记存放在session中。这个场景中可能出现没有session存在的情况,正常的判断应该是这样:



private boolean ifFlagExistInSession(HttpServletRequest request) {     
HttpSession session = request.getSession(false);     
if (session != null) {        
if (session.getAttribute("flagName")   != null) {             
return true;         
}     
}   
return false;

 



而下面的写法,则可能会生成一个新的不在我们意图之外的session:


private boolean ifFlagExistInSession(HttpServletRequest request) {    
 HttpSession session = request.getSession();   // a new session created if no session exists    
 if (session.getAttribute("flagName")   != null) {        
return true;      
}    
return false;} 




注意request.getSession() 等同于 request.getSession(true),除非我们确认session一定存在或者sesson不存在时明确有创建session的需要,否则请尽量使用request.getSession(false)。

FeedBack:
# re: 谁在创建session(1)-不恰当的request.getSession()
2007-12-19 15:33 | 隔叶黄莺

一般的(可能有些servlet实现不是这样的),默认的访问用户第一次 jsp 页面就会创建 session 的,因为 jsp 中指令 session 配置为 true,即
<%@ page session="true"%>

编译出来的的 java 文件在 _jspService() 方法中有代码行(Tomcat是这样的)

session = pageContext.getSession();

除非你显示设置
<%@ page session="false"%>
才会让你自己 getSession(true)或 getSession()时创建session

其实创建一个 session 并不耗什么资源,无非就是一个空的map,就是别往里面塞太多的东西,尤其是在集群环境下,会增加同步的负担。

Success时,



//Struts Bean方法里session的用法   
String login_name = rs.getString("true_name");   //返回和请求相关的session   
HttpSession session = request.getSession();   //把truename的属性值login_name保存在session对象中  
session.setAttribute("truename", login_name);  




False时,

LoginFalse.loginFalse(request); 


即:调用了LoginFalse类里面的俄静态方法,当然是自己写的,最近刻意养成把所有的东西给封装的习惯,感觉不错。LoginFalse里面的代码,


 public static void loginFalse(HttpServletRequest request) {      
String login_false = "Your username or password is wrong!!!";        HttpSession session = request.getSession();      
session.setAttribute("loginfalse", login_false); } 




在login.jsp的代码,




<%String loginwrong = (String) session.getAttribute("loginfalse");    if (loginwrong != null) { %>    <%=loginwrong%>    <%    //销毁session    session.removeAttribute("loginfalse");    } session.removeAttribute("truename"); %> 




每页需要用 <%@ include file="inc/logout.inc" %> 来显示用户的true_name以及logout功能实现。
logout.inc代码,



<%String u = (String) session.getAttribute("truename");%>   
<%=u%>  
<%if (u == null) {%>   
<logic:forward name="g_login"/>   <%}%>   
<html:link page="/login.jsp">logout</html:link>  
 






还有LoginForm里面的not required处理就省略了。
自我感觉这次的问题就出现在,不知道Struts里面scope定义session的话,在Bean里面不人为写session时,struts会自己给个getSession();
还有跟以前在JSP-JSP里面的session有点不同,就在这:



HttpSession session = request.getSession(); 


session.setAttribute之前必须得注意写上这一行。

转自http://www.cnblogs.com/lingxue3769/archive/2010/12/21/1912661.html
分享到:
评论

相关推荐

    request.getSession().doc

    2. 在检查 Session 中是否存在某个变量或标记时,未使用 getSession(false) 方法,从而导致不必要的会话创建。 最佳实践 为了避免上述错误,可以遵循以下最佳实践: 1. 在使用 getSession() 方法时,明确指定 ...

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

    【官方解释】 getSession 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 ...

    自己实现的spring-session

    如果没有sessionId就新创建session,如果有sessionId,就去redis中查看是否有此id的记录,如果没有就新建session,如果有,还是新建session,并把redis中此session的相关数据赋值给新建的session,最后保存sessionId...

    基于servlet的购物车

    //得到书号和书本对象 ...// System.out.println("SESSION===================&gt;"+request.getSession().getAttribute("shoppingCart")); request.getRequestDispatcher("listcart.jsp").forward(request, response);

    java-servlet-api.doc

    当Session终止时,服务器会释放Session对象以及所有绑定在Session上的对象。 绑定对象到Session中 如果有助于你处理应用的数据需求,你也许需要绑定对象到Session中,你可以通过一个唯一的名字绑定任何的对象到...

    数据库测试test.sql

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

    用户管理系统(ums)

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

    登录过滤器

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

    Java类写的随机验证码

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

    java小项目

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

    session、cookie的跨域共享

    可以简单告诉你session不是我们大都认为的在登录时候,通过request.getSession()产生的,而是你在首次访问一个应用时候,就已经产生了,这个在我的代码里有ActiveUserListener.java这个session创建的监听器....

    jsp基础精华详解

    HttpSession session = request.getSession(); session.setAttribute("name", "zhangsan"); session.setAttribute("pwd", "aaa"); String name = (String) session.getAttribute("name"); 2.cookie: //创建Cookie ...

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

    jsp+Servlet实现简单的登陆

    Servlet+Jsp实现简单的登陆,HttpSession session = request.getSession();

    网上购物系统设计与实现

    HttpSession session=request.getSession(); CartBean cb=new CartBean(); Vector&lt;CartProduct&gt; cart =(Vector)session.getAttribute("cart"); String id=request.getParameter("id"); if(cart==null){ cart=...

    购物网站系统

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

    比较简单的添加购物车,不过只有一个小程序

    HttpSession session=request.getSession(); ShopCart cart=(ShopCart)session.getAttribute("cart"); if(cart==null){ cart=new ShopCart(); session.setAttribute("cart", cart); } String id=...

    struts乱码问题

    HttpSession session=request.getSession(); session.setAttribute("bookName", this.bookName); session.setAttribute("bookPrice", this.bookPrice); session.setAttribute("bookPress", this.bookPress); ...

    jxl Java导出Excel文件jar 包

    HttpSession session = request.getSession(); //读取学生集合 List&lt;Student&gt; students = (List) session .getAttribute("students"); //读取学生编号集合 List&lt;String&gt; stuid =(List&lt;String&gt; )...

    Struts2实战总结

    1:在action中定义的变量,在jsp页面中显示用:变量名" /&gt; ...Map session = ActionContext.getContext().getSession(); HttpServletRequest request = ServletActionContext.getRequest (); 设置它们的值的方法

Global site tag (gtag.js) - Google Analytics