Struts1.2 驗證用戶是否登陸 兩種方法
項目中一般需要做驗證用戶是否登陸,沒登陸就不能進入ACTION執行后臺代碼等的需要。
第一種
為所有ACTION做一個BaseAction(此類 extends Action)
此類重載execute方法 ,部分實例代碼 ,根據個人需要去定
/**
* override method.
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
super.execute(mapping, form, request, response);
//用戶如果未登錄或session過期,則轉向登錄動作。
if (!isLogin(request))
return mapping.findForward("login");
try
{
ActionForward forward = doExecute(mapping, form, request, response);
//重新生成token
//super.saveToken(request);
return forward;
} catch (Exception e)
{
logger.error(e);
e.printStackTrace();
return mapping.findForward("systemError");
}
}
/**
* 判斷用戶是否已經登錄。
*
* @param request
* @return
*/
protected boolean isLogin(HttpServletRequest request)
{
return request.getSession().getAttribute(Session_User) != null;
}
這樣寫后,以后所有ACTION都繼承此類,然后重寫doExecute方法即可
GradeAction extends BaseAction
在doExecute方法 寫操作代碼
第二種
也是做個BaseAction繼承DispatchAction,然后所有ACTION繼承此BaseAction
BaseAction主要代碼片段
/**
* override method.
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{ //用戶如果未登錄或session過期,則轉向登錄動作。
if (!isLogin(request))
return mapping.findForward("sessionEnd");
try
{
// ActionForward forward = new ActionForward();
//重新生成token
//super.saveToken(request);
return super.execute(mapping, form, request, response);
} catch (Exception e)
{
// logger.error(e);
e.printStackTrace();
return mapping.findForward("systemError");
}
}
以后所有類繼承此基類
LinkAction extends ActionX
由于DispatchAction特點,所有繼承BaseAction的類都可以正常寫單獨方法完成。