Struts2验证用户登录两种方法

项目中一般需要做验证用户是否登陆,没登陆就不能进入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的类都可以正常写单独方法完成。

至此两种验证见效。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值