struts2小小项目 经验总结(2) 拦截器

  1. 如果说一个网站可以直接访问到需要登录后才能访问的网页,这是很失败的,所以,必须实现这样一个功能,就是客户端不可以直接访问非登录界面的网页,这个功能可以使用struts2的拦截器来实现,就是如果有用户赋值拿已经登录的网页粘贴访问的话,是会跳到登录界面的。
  2. 要使用struts2的拦截器,要在配置配置文件中配置好拦截器,做法是酱紫的
    1. 在struts.xml的package标签中配置拦截器
              <!--使用interceptors声明一个拦截器-->
              <interceptors>
                  <interceptor name="authotity" class="intercepter.AuthorityInterceptor"/>
              </interceptors>

      包括声明拦截器的名字和它的实现类,实现类如下

      package intercepter;
      
      import action.dao.DbBean;
      import com.opensymphony.xwork2.ActionContext;
      import com.opensymphony.xwork2.ActionInvocation;
      import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
      
      import java.util.Map;
      /**
       * Demo class
       *
       * @author lin
       * @date 2018/11
       * 拦截器类
       */
      public class AuthorityInterceptor extends AbstractInterceptor {
      
          @Override
          public String intercept(ActionInvocation invocation) throws Exception{
              ActionContext actionContext = invocation.getInvocationContext();
      
              String name  =  invocation.getInvocationContext().getParameters().get("name").getValue();
              String pass =  invocation.getInvocationContext().getParameters().get("pass").getValue();
      //        通过上面的方法获得从jsp界面表单传过来的name和pass
              
              DbBean dbBean = new DbBean(name, pass);
      //        实例化一个数据库bean实例
              
      //        使用数据库bean实例的验证登录方法来验证是否为合法输入,如果是则不拦截,否则返回login,
      //        跳回index.jsp
              if(dbBean.verifyLogin()){
                  return invocation.invoke();
              }
              actionContext.put("tip", "还没有登录~~");
              return "login";
          }
      }
      
    2. 然后在需要使用拦截器拦截的action下配置,需要注意的是,要先用默认的拦截器拦截之后,才可以使用自定义的拦截器拦截

            <action name="loginAction" class="action.Actions.LoginAction">
                  <result>searchPics.jsp</result>
                  <result name="error">index.jsp</result>
                  <result name="login">index.jsp</result>
                  <interceptor-ref name="defaultStack"/>
                  <interceptor-ref name="authotity"/>
              </action>

猜你喜欢

转载自blog.csdn.net/weixin_39452731/article/details/84888423