Struts2自定义拦截器进行访问限制

来源:互联网 发布:博罗网络问政主页 编辑:程序博客网 时间:2024/06/07 01:17

Struts2自定义拦截器进行访问限制:

1、自定义拦截器类,实现Interceptor接口或者继承AbstractInterceptor类:
package com.interceptor;

import com.opensymphony.xwork2.Action;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.AbstractInterceptor;/** * @author  李芝成* @date 创建时间:2017年4月17日 下午8:33:59 * @version 1.0 * 项目名:SSHDemo* 包名:com.interceptor* 描述: */   public class BaseInterceptor extends AbstractInterceptor{    public String intercept(ActionInvocation arg0) throws Exception {        //获取Actioncontext        ActionContext actionContext=ActionContext.getContext();        //获取user对象        Object user=actionContext.getSession().get("user");        if (user!=null) {            //继续向下执行            return arg0.invoke();        }else {            actionContext.put("msg", "您还没登录,请先登录");            return Action.LOGIN;//如果用户还没登录,返回login值        }    }}

2、在struts.xml配置文件中自定义拦截器:

<!--声明拦截器 --><interceptors>    <interceptor name="baseinterceptor"         class="com.interceptor.BaseInterceptor"/>    <!--定义一个拦截器栈,所有拦截器都放在栈中按顺序执行 -->    <interceptor-stack name="mystack">        <!-- 默认拦截器 -->        <interceptor-ref name="defaultStack"></interceptor-ref>        <!-- 自定义拦截器 -->        <interceptor-ref name="baseinterceptor"></interceptor-ref>    </interceptor-stack></interceptors>

3、在struts.xml配置文件action中使用拦截器:

<action name="userAction_add" class="userAction">    <result name="login">/login.jsp</result>    <result name="success">/success.jsp</result>    <!--在action中使用自定义拦截器 -->    <interceptor-ref name="mystack"/></action>
0 0
原创粉丝点击