struts2自定义拦截器注解配置方法

来源:互联网 发布:apache logo 编辑:程序博客网 时间:2024/06/05 04:58

自定义拦截器:

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{    }
0 0
原创粉丝点击