2012年11月16日 星期五

Struts 1.3 redirect function in login page

1. Problem: 

In my application,
I have a login.jsp and
authorize page need the user to login through this login,
then he will get the content of authorize page.

A general method
in struts-config.xml  file
<action path="/login" type="struts.action.LoginAction" scope="session" name="loginForm">

            <forward name="login" path="/login" />   
            <forward name="success" path="/loginSuccessPage" />
</action>
<action path="/anyAuthorizePage" type="struts.action.AuthorizeAction" scope="request" >
            <forward name="login" path="/login" />
            <forward name="anyAuthorizePageSuccess" path="/anyAuthorizePageSuccessPage" />
 </action>


And long as you type following page, and assuming session is timeout
                     http://localhost/anyAuthorizePage
the action is AuthorizeAction and because not login,
user will receive the login.jsp.

But when the user login,
according to the login action,
user will receive the loginSuccessPage,
not user expected the anyAuthorizePageSucccessPage.



2. Solution:

My solution conception is
let client way provide redirect url to LoginAction, 
and LoginAction use this redirect url to perform the redirection page.

The key point in my solution is client way, therefore I don't handle any session  this in anyAuthorizeAction. I only focus on the client way and LoginAction.
Another reason why I solve in client way is me observe that the



3. Example:

The technique contains the javascript to get the browseURL, struts action of redirect attribute. The following simple step is following:

A. Adding the webbrowse url filed on login.jsp

 
<script type="text/javascript">

/*將 user browserID */
function loginOnload() {
    writeBrowseUrlToForms();
}


/* 寫入 browse URL 到欄位中 */
function writeBrowseUrlToForms() {
   
    // 取得所有表單的 form, 因為 tagname 會回傳 array 
    elementsForms = document.getElementsByTagName("form");
   
    // 進入個別 form 取得個別欄位
    for (var intCounter = 0; intCounter < elementsForms.length; intCounter++)
    {
           writeBrowseUrlToForm(elementsForms[intCounter]);
    }
}

/*單一 URL */
function writeBrowseUrlToForm(currentForm) {

     var elementsInputs;
     var browseurl = document.location.href;
    
     // 取得所有輸入欄位 input, 但只在意 formposition 與 endPosition 兩個欄位
     elementsInputs = currentForm.getElementsByTagName("input");

     for (var intCounter = 0; intCounter < elementsInputs.length; intCounter++)
     {
           var inputFieldName = elementsInputs[intCounter].name;
           var inputFieldValue = elementsInputs[intCounter].value;
          
           if (inputFieldName == "browseurl")
           {
              elementsInputs[intCounter].value = browseurl;
           }
     }

}

/* 加入 Layout Onload 到事件中*/
// Namespace of login content
var login;

if (!login) {
    login = {};
}

login.oldOnload = window.onload || function() {};
window.onload = function () {
    login.oldOnload();
    loginOnload();
};

</script>
<html:form action="/login" >

<%-- hidden the url redirect, and on submit send to user --%>
<table id="login_table" style="border-collapse: collapse">
      
    <tr>
    <td>User Name</td>
    <td><html:text name="loginForm" property="name" size="20" /></td>
    </tr>
    
    <tr>
    <td>Password</td>
    <td> <html:password name="loginForm" property="password" size="21" /></td>
    </tr>
    
        
    <%-- Hiden redirect page --%>
    <tr>
     <html:hidden property="browseurl" value=""/>
    </tr>
    
    <tr> <td colspan="2" align="right">    <html:submit value="login"/></td>
    </tr>
    
    
    
</table>

</html:form>



 B. And LoginAction adding sendRedirect() method in LoginAction

public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
 
if (verifyUser(username, password)) {
           
          ....
       
            // 如果需要重導入功能
            ActionRedirect redirect = null;
            if ( (redirect = sendRedirect(request, loginForm.getBrowseurl(), mapping)) != null) {
                return redirect;
            }else {
                return mapping.findForward("success");
            }
        } 

}

}


    protected ActionRedirect sendRedirect(HttpServletRequest req, String needLoginPageURL, ActionMapping mapping) {
        ActionRedirect redirect = null;
       
        if (req == null || needLoginPageURL == null || needLoginPageURL.equals("")) {
            return redirect;
        }
        logger.info(needLoginPageURL);
       
        // 比對是否相同 host not by hack
         if (equalsHost(getThisFormUrl(req), needLoginPageURL)) {
           
             String contextPath = getContextPath(needLoginPageURL);
           
             if (contextPath != null) {
               
                 // 手動加入想要 login 內容
                 if (contextPath.contains("/authorizePage.do")) {
                     redirect = new ActionRedirect(mapping.findForward("
authorizePage"));
                 }
               
             } // end if path
         }
        return redirect;
    }



/** 需要 URL 網址 */
    protected String getThisFormUrl(HttpServletRequest req) {
        String reqUrl = req.getRequestURL().toString();
        String queryString = req.getQueryString();  
        if (queryString != null) {
            reqUrl += "?"+queryString;
        }
        return reqUrl;
    }



C. LoginForm.class add the browseurl

public class LoginForm extends ActionForm{
    private static final long serialVersionUID = 1L;
    private String name;
    private String password;
    private String browseurl;        // 如果需要從新導入可以使用
   
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getBrowseurl() {
        return browseurl;
    }
    public void setBrowseurl(String browseurl) {
        this.browseurl = browseurl;
    }
     
}

D. Setting the struts.xml Action
<action path="/login" type="struts.action.LoginAction" scope="session" name="loginForm">
            <forward name="login" path="/login" />   
            <forward name="success" path="/successLogin" />           
           <forward name="authorizePage" path="/authorizePaget.do" redirect="true" />
</action>



Reference
Struts_Action_Redirct
GET_Browse_URL
web_GET_URL

沒有留言:

張貼留言