struts2的Interceptor

本文介绍如何在Struts2框架中定义和使用自定义拦截器。通过实现Interceptor接口并重写intercept方法来创建拦截器类。此外,在struts.xml配置文件中定义了拦截器及其栈,并应用于特定Action。

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

一.定义拦截器类,实现Interceptor接口,重写里面的方法:

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

public class MyInterceptor implements Interceptor {


public String intercept(ActionInvocation invocation) throws Exception {
Object user = ActionContext.getContext().getSession().get("userkey");
if(user != null)
return invocation.invoke(); //表示被拦截到的方法继续会执行action
ActionContext.getContext().put("requestKey", "�㻹û�е�½");
return "success";
}
public void init() {
}
public void destroy() {
}

}


二.配置struts2的配置文件:

<struts>
<!-- 禁止对action方法的动态调用 -->
<constant name="struts.enable.DynamicMethodInvocation" value="false"/>
<!-- 指定访问action的后缀类型 -->
<constant name="struts.action.extension" value="action"></constant>

<!-- 将struts2的ui设置为simple -->
<constant name=”struts.ui.theme”value=”simple”/>

<!-- 将struts2的ObjectFactory交给spring管理 -->
<constant name="struts.ObjectFactory" value="spring"></constant>


<package name="default" namespace="/myaction" extends="struts-default">
<!--
在bean.xml中定义拦截器:
写入自己定义的拦截器
编写拦截器栈,包括系统默认的拦截器和自己定义的拦截器
最后再想调用拦截器的action中加入拦截器栈
-->
<interceptors>
<interceptor name="mi" class="com.interceptor.MyInterceptor"></interceptor>
<interceptor-stack name="mistack">
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="mi"></interceptor-ref>
</interceptor-stack>
</interceptors>

———— <default-interceptor-ref的意思是设置mistack为该包下的默认拦截器。(如果action中有则执行action中的拦截器不执行默认的)
<default-interceptor-ref name="mistack"></default-interceptor-ref>
<global-results>
<result name="success">/WEB-INF/page/hello.jsp</result>
</global-results>
<action name="hello_*" class="com.action.Hello" method="{1}">
<interceptor-ref name="mistack"></interceptor-ref>
</action>
</package>
<!-- Add packages here -->
</struts>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值