附:Struts2-CRM,拦截器实现权限访问

时间:2023-03-09 02:16:57
附:Struts2-CRM,拦截器实现权限访问

拦截器代码: 

package mycrm.interceptor;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

import mycrm.domain.User;

public class PrivilegeInterceptor extends MethodFilterInterceptor {

    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {
        //判断session是否有用户信息
        User existUser = (User) ServletActionContext.getRequest().getSession().getAttribute("existUser");
        if(existUser == null){
            //没有登陆,给出提示信息,回到登录页面
            //获取当前Action
             ActionSupport actionSupport = (ActionSupport) invocation.getAction();
             actionSupport.addActionError("没有权限,请登录后再访问!");
             //回到登录页面
             return actionSupport.LOGIN;
        }else{
            //已经登录,放行,执行下一个拦截器
            return invocation.invoke();
        }
    }

}

向配置文件添加拦截器:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>

<package name="action" extends="struts-default" namespace="/">

<!-- 定义拦截器 -->
<interceptors>
<interceptor name="privilegeInterceptor" class="mycrm.interceptor.PrivilegeInterceptor"/>
</interceptors>

<!-- 全局页面 -->
<global-results>
<result name="login">/login.jsp</result>
</global-results>

<!-- 配置Customer的Action -->
<action name="customer_*" class="mycrm.action.CustomerAction" method="{1}">

<result name="findAll">/jsp/customer/list.jsp</result>
<result  name="add">/jsp/customer/add.jsp</result>
<result name="addSuccess">/jsp/customer/list.jsp</result>

<!-- 添加拦截器,登录和注册不拦截 -->
<interceptor-ref name="privilegeInterceptor">
<param name="excludeMethods">login</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"/>

</action>

<!-- 配置User的Action -->
<action name="user_*" class="mycrm.action.UserAction" method="{1}">

<result name="login">/login.jsp</result>
<result type="redirect">/index.jsp</result>

<!-- 添加拦截器,登录和注册不拦截 -->
<interceptor-ref name="privilegeInterceptor">
<param name="excludeMethods">login</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"/>

</action>

</package>
</struts>

 设置表单target放置页面嵌套:

  <FORM id=form1 name=form1 action="${pageContext.request.contextPath }/user_login.action" method=post target="_parent">