星期五, 1月 25, 2013

[JSP] jsp session getAttribute跟setAttribute都爆炸了 XD

機器上測試用OpenJDK做的session操作整個爆掉(不能取/不能建session)。
都會噴以下二個exception:
setAttribute: Session already invalidated
getAttribute: Session already invalidated

以下是成功於正常的Oracle JDK成功操作session的測試碼,移到新的環境就會爆掉XD

//try{

 HttpSession httpsession = request.getSession(false);
 
 if(httpsession == null){
  System.out.println("HttpSession null");
 }else{
  System.out.println("HttpSession:" + httpsession.getId());
 }
 
  if(httpsession.getAttribute("test") == null){
 
   //throw getAttribute: Session already invalidated
 //if(session.getAttribute("test") == null) { 
   System.out.println("Session not found");
   
   try{
    
    System.out.println("Start to craete session");
    
    //request.getSession(true).setAttribute("test", "HelloSession");
    //session.setAttribute("test", "HelloSession");
    //httpsession.setAttribute("test", "HelloSession");
    
    HttpSession newSession = request.getSession(true);
    if(newSession.isNew()){
     System.out.println("isNew session id:" + newSession.getId());
    }else{
     System.out.println("old session id:" + newSession.getId());
    }
   
    newSession.setAttribute("test", "HelloSession");
    
    System.out.println("Suceed to craete session");
  
    
   }catch(IllegalStateException illeagalStateEx){
    System.out.println("Fail to craete session:" 
          + illeagalStateEx.getMessage());
   }
   
  }else{
   
   System.out.println("Session found");
   
   String sessionValue = 
     (String)httpsession.getAttribute("test");
   
   System.out.println("sessionValue:" + sessionValue);
   
  }
//}catch(Exception ex){
 
 //System.out.println("Global Exception:" + ex.getMessage());

//}



setAttribute: Session already invalidated

You can test it with HttpServletRequest#getSession(boolean create) with create=false. It will return null if not created yet.
HttpSession session = request.getSession(false);
if (session == null) {
    // Session is not created.
} else {
    // Session is already created.
}
If you actually want to create the session anyway if it doesn't exist, then just grab it and test the freshness using HttpSession#isNew():
HttpSession session = request.getSession();
if (session.isNew()) {
    // Session is freshly created during this request.
} else {
    // Session was already created during a previous request.
}
That was how you would do it in a Servlet. In a JSP you can only test the freshness with help of JSTL and EL. You can grab the session by PageContext#getSession() and then just call isNew() on it.
<c:if test="${pageContext.session.new}">
    <p>Session is freshly created during this request.</p>
</c:if>
or
<p>Session is ${pageContext.session.new ? 'freshly' : 'already'} created.</p>


java.lang.IllegalStateException: Cannot create a session after the response has been committed


Reference:
对异常 java.lang.IllegalStateException: getAttribute: Session already invalidated的理解

沒有留言:

張貼留言

留個話吧:)