2010-10-20 98 views
2

沒有設置我有一個春天控制器,它是把一個變量在會話:Session變量春

public class LoginFormController extends SimpleFormController { 

    public ModelAndView onSubmit(HttpServletRequest request, 
      HttpServletResponse response, Object command) throws Exception { 

      request.getSession().setAttribute("authenticated_user", "authenticated_user"); 
    } 
} 

然後我有一個HandlerInterceptor接口。在preHandle方法,我檢查變量會話:

public boolean preHandle(HttpServletRequest request, 
             HttpServletResponse response, 
             Object handler) throws Exception { 

     /* first, check if the requested view even required authentication */ 
     if (isAuthenticationRequired(request)) { 

      /* check to see that user is logged in */ 
      if (null == request.getSession().getAttribute("authenticated_user")) { 
       forwardToLogonPage(request, response); 
       return false; 
      } 
      /* all is ok - pass the request on */ 
      return true; 
     } 
     /* all is ok - pass the request on */ 
     return true; 
    } 

問題是,它似乎是會話變量沒有被自request.getSession()設置的getAttribute(「AUTHENTICATED_USER」))始終。解決爲空。

任何想法plz?

感謝, Krt_Malta

+0

BDW Request對象...的isAuthenticationRequired方法效果很好,我測試了它。 – 2010-10-20 06:41:26

+0

問題實際上是onSubmit()方法沒有被調用... – 2010-10-20 07:15:23

回答

0

嘗試throw new ModelAndViewDefiningException(new ModelAndView("logonPage")),而不是return false

而在你logonPage,明確包括在表單標籤的動作,這樣的事情:

<form:form method="post" commandName="login" action="logonPage.htm"> 
0

您也可以注入ServletRequestAttributes。 通過包括:

import org.springframework.web.context.request.ServletRequestAttributes; 
import org.springframework.web.context.request.RequestContextHolder; 

我在一個抽象的超控制器這樣做,所以我的所有控制器都將servlet請求知道。

要提取您使用可以使用以下

protected ServletRequestAttributes getServletRequest(){ 
    return (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); 
    }