Struts2自定拦截器

本文介绍如何在Struts2框架中实现自定义拦截器,包括编写拦截器类、配置拦截器及如何与默认拦截器配合使用等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义拦截器
1、编写一个类,实现com.opensymphony.xwork2.interceptor.Interceptor
2、主要实现public String intercept(ActionInvocation invocation) throws Exception{}方法
该方法的返回值就相当于动作的返回值
如果调用了String result = invocation.invoke();得到了动作类的返回的值。
public String intercept(ActionInvocation invocation) throws Exception {
		//判断用户是否登录
		HttpSession session = ServletActionContext.getRequest().getSession();
		Object obj = session.getAttribute("user");
		if(obj==null){
			return "login";
		}else{
			return invocation.invoke();//调用动作方法
		}
	}


3、拦截器定义好后,一定要在配置文件中进行注册:
<interceptors> 只是定义拦截器,并没有起作用 
<interceptor name="permissionInterceptor" class="cn.itcast.interceptor.PermissionInterceptor"></interceptor>
</interceptors>
4、配置文件中的动作,要通过
<interceptor-ref name="permissionInterceptor"></interceptor-ref>使用该拦截器
注意:一旦动作中使用了自定义的拦截器,那么默认的就不起作用了。一般应该采用如下的做法:
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="permissionInterceptor"></interceptor-ref>

多个动作类都要使用的话,可以通过package来进行组合。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值