一个struts2的自定义拦截器示例
在你的应用程序中使用自定义拦截器是提供跨切割应用程序功能的简洁方式。
创建自定义拦截器很容易,需要扩展的是以下Interceptor接口:
public interface Interceptor extends Serializable{ void destroy(); void init(); String intercept(ActionInvocation invocation)throws Exception; }
init()方法提供了一种初始化拦截器的方法,而destroy()方法为拦截器清理提供了一个工具。与action不同,拦截器在请求之间重复使用,需要线程安全,特别是intercept()方法。
ActionInvocation对象可访问运行时的环境。它允许访问action本身以及方法来调用action,并确定action是否已被调用。
如果你不需要初始化或清理代码,可以扩展AbstractInterceptor类,以实现init()和destroy()的默认的无操作指令。
创建自定义拦截器类MyInterceptor
public class MyInterceptor extends AbstractInterceptor { @Override public String intercept(ActionInvocation actionInvocation) throws Exception { /* let us do some pre-processing */ String output = "Pre-Processing"; System.out.println(output); /* let us call action or next interceptor */ String result = actionInvocation.invoke(); /* let us do some post-processing */ output = "Post-Processing"; System.out.println(output); return result; } }
创建Action类HelloWorldAction
public class HelloWorldAction extends ActionSupport { private String name; public String execute() throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); String name = request.getParameter("name"); System.out.println("Inside action...."); System.out.println("name = " + name); return "success"; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
struts.xml相关配置
<!--注意拦截器的配置顺序,应置于action前-->
<interceptors> <interceptor name="myinterceptor" class="daidao.s2sm.interceptor.MyInterceptor" /> </interceptors> <action name="hello" class="daidao.s2sm.web.HelloWorldAction" method="execute"> <interceptor-ref name="params"/> <!--自定义拦截器声明--> <interceptor-ref name="myinterceptor" /> <result name="success">/WEB-INF/views/HelloWorld.jsp</result> </action>
参考链接:https://www.w3cschool.cn/struts_2/struts_interceptors.html

浙公网安备 33010602011771号