1. 程式人生 > >struts2自定義攔截器註解配置方法

struts2自定義攔截器註解配置方法

自定義攔截器:

package com.penjing.interceptor;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.penjing.entity.Role;
import
com.penjing.entity.User; public class RoleManageInterceptor implements Interceptor{ /** * */ private static final long serialVersionUID = 1L; private JSONObject result; public JSONObject getResult() { return result; } @Override public void destroy() { // TODO Auto-generated method stub
} @Override public void init() { // TODO Auto-generated method stub } @Override public String intercept(ActionInvocation invocation) throws Exception { // TODO Auto-generated method stub HttpServletRequest request = (HttpServletRequest)invocation.getInvocationContext().get(ServletActionContext.HTTP_REQUEST); User user = (User)request.getSession().getAttribute("user"
); if(user != null){ Role role = (Role)request.getServletContext().getAttribute("role_"+user.getRoleId()); if(role !=null){ if(role.getManageRole()){ return invocation.invoke(); } } }else{ return "noLogin"; } return "noRoleAuthority"; } }

Struts.xml:

<?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>  
    <constant name="struts.action.extension" value="," />
    <package name="crud-default" extends="json-default">
        <interceptors>
            <!-- 角色管理許可權攔截器 -->
            <interceptor name="roleManageInterceptor"
            class="com.penjing.interceptor.RoleManageInterceptor">
            </interceptor>

            <!-- 角色管理許可權攔截器棧 -->
            <interceptor-stack name="roleInterceptor">
                <interceptor-ref name="roleManageInterceptor"/>
                <interceptor-ref name="defaultStack" />
            </interceptor-stack>


        </interceptors>
    </package>
</struts>

因為action中需要使用json資料,所以在包中繼承的是json-default

action中的配置:

@ParentPackage(value="crud-default")
public class RoleAction extends ActionSupport implements ServletRequestAware,ServletContextAware{
}
@Action(value="/role/saveRole",
            interceptorRefs={@InterceptorRef("roleInterceptor")},
            results={@Result(name="noLogin",type="chain",location="loginErrorAjax"),
                    @Result(name="noRoleAuthority",type="chain",location="noAuthorityAjax")
            })
    public String saveRole() throws Exception{
    }