struts2 配置拦截器

(1)通过<interceptor......./>元素来定义拦截器

(2)通过<interceptor-ref................/>元素来使用拦截器

自定义拦截器  实现interceptor 接口,继承Abstract Interceptor

编写权限验证拦截器,代码如下:

package intercepter;

import java.util.Map;

import com.opensymphony.xwork2.ActionInvocation;

import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

import entity.Users;

/**

 * 权限验证拦截器

 * @author bao

 *

 */

@SuppressWarnings("serial")

public class UserInterceptor extends AbstractInterceptor {

/**

 * 拦截器的拦截方法

 */

@Override

public String intercept(ActionInvocation invocation) throws Exception {

//获取用户回话信息

Map session = invocation.getInvocationContext().getSession();

Users users = (Users)session.get("user");

if(users == null){

//终止执行,返回登录页面

return "input";

}else{

//继续执行剩余的拦截器和Action

return invocation.invoke();

}

}

}

然后在配置文件中,定义拦截器并引用它,配置文件的内容如下:

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

     <interceptors>

     <interceptor name="userInterceptor" class="intercepter.UserInterceptor"></interceptor>

     <interceptor-stack name="myStack">

     <interceptor-ref name="defaultStack"></interceptor-ref>

     <interceptor-ref name="userInterceptor"></interceptor-ref>

     </interceptor-stack>

     </interceptors>

<!--定义默认拦截器-->

     <default-interceptor-ref name="myStack"></default-interceptor-ref>

     <global-results>

     <result name="input">/login.jsp</result>

     </global-results>

<!--EndFragment-->

猜你喜欢

转载自bao1073740756-126-com.iteye.com/blog/1443440