struts2-拦截器的基本使用

从struts2框架来看,拦截器几乎完成了Struts 2框架70%的工作,包括解析请求参数,将请求参数赋值给Action 属性,执行数据校验,文件上传等。Struts 2设计的灵巧性,更大程度地得益于拦截器设计,当需要扩展Struts 2功能时,只需提供对应拦截器,并将它配置在Struts2容器中即可:如果不需要该功能,只需取消该拦截器的配置即可。

接下来我们定义一个权限验证拦截器。

1、首先在登录成功后的界面做一个a标签;
struts2-拦截器的基本使用
2、修改Action实现类,将登录的用户名存到“userlll”中,后面用拦截器判断是否有权限进链接;

struts2-拦截器的基本使用

3、建立一个自定义拦截器;
struts2-拦截器的基本使用

package com.interceptor;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

@SuppressWarnings("serial")
public class UserInterceptor implements Interceptor{
	public String intercept(ActionInvocation arg0) throws Exception
	{
		System.out.println("拦截器已启动");
		String strName=(String) ActionContext.getContext().getSession().get("userlll");
		if(strName.equals("1"))
		{
			String str = arg0.invoke();
			System.out.println(str);
			System.out.println("拦截器已结束");
			return str;			
		}
		else
		{
			ActionContext.getContext().getSession().put("tip", "您没有权限查看");
			return "output";
		}	
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub
		
	}
}

从上面的代码看,拦截器主要是依据session中的username变量的值来判断用户是否是我规定有权限的用户(用户1)。

4、配置相应的struts.xml
struts2-拦截器的基本使用
执行我前面定义的标签,直接上配置,注意一下箭头的属性名,都是细节的东西。
struts2-拦截器的基本使用
5、结果
struts2-拦截器的基本使用
struts2-拦截器的基本使用
struts2-拦截器的基本使用
struts2-拦截器的基本使用
struts2-拦截器的基本使用