struts 2.0拦截器如何进行权限验证,实现某些登录的用户能访问,别的不能访问该页面,别的用户要访问话要提示它先登录,怎样拦截某一具有权限的用户能访问,无权限的不能访问,希望 提供一些代码示例,和说明。

解决方案 »

  1.   

    —_—
    1、配个拦截器
    struts2 guide有说
    2、用户里面添加一个标志权限或角色的标志
    表里加个列
    3、在拦截器里读取,判断用户的的权限或角色类型
    类型
    读取访问用户要访问的action
    判断是否有权限。
    类似filter
      

  2.   

    拦截器类
    public class AuthInterceptor extends AbstractInterceptor
    {
     @Override
            //去除警告
     @SuppressWarnings("unchecked")
     public String intercept(ActionInvocation invocation) throws Exception
     {
                    //获取session
      Map map = invocation.getInvocationContext().getSession();
      //判断是否为空
      if(map.get("user") == null)
      {
       return Action.LOGIN;
      }
      else
      {
       return invocation.invoke();
      }
     }action类
    public String execute() throws Exception {
        if("abc".equals(this.getUsername())&&"abc".equals(this.getPassword())){
         Map map = ActionContext.getContext().getSession();
                       //往session中注入值
         map.put("user", "abc");
         return "welcome";struts.xml文件<interceptors>
             <interceptor name="auth" class="interceptor.AuthInterceptor">
             
      </interceptor>
    </interceptors><global-results >
      <result name ="login" type="redirect">/input.jsp</result>
    </global-results><action name="register" class="com.RegisterAction" >
     <result name="input">/register.jsp</result>
     <result name="success">/success.jsp</result>
     <interceptor-ref name = "auth"></interceptor-ref>
     <interceptor-ref name = "defaultStack"></interceptor-ref>
    </action>