建立一个过滤器对象,实现对action对象当中所指定的方法进行拦截操作:
登录界面:login
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="SomeAction"> <input type="submit" value="提交"> </form> <a href="SomeAction_doFirst">doFirst</a> <a href="SomeAction_doSecond">doSecond</a> <a href="SomeAction_doThird">doThird</a> </body> </html>action对象
package com.action; import com.opensymphony.xwork2.Action; /** * * @author Administrator * */ public class SomeAction implements Action{ @Override public String execute() throws Exception { System.out.println("执行execute方法"); return "success"; } /** * 必须要将方法设置为public否则服务器对象将无法找到该方法,从而产生无法找到方法的异常 */ public String doFirst() { System.out.println("执行doFirst方法"); return "success"; } public String doSecond() { System.out.println("执行doSecond方法"); return "success"; } public String doThird() { System.out.println("执行doThird方法"); return "success"; } }方法拦截器对象:
package com.intercept; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor; /** * * @author Administrator *自定义一个过滤器对action对象当中的方法进行过滤操作 */ public class MyIntercept extends MethodFilterInterceptor{ /* (non-Javadoc) * @see com.opensymphony.xwork2.interceptor.MethodFilterInterceptor#doIntercept(com.opensymphony.xwork2.ActionInvocation) * 通过invocation调度对象来对请求对象的控制权限进行转交操作 */ @Override protected String doIntercept(ActionInvocation invocation) throws Exception { System.out.println("对action类当中指定的方法进行过滤操作"); return invocation.invoke(); } }在struts.xml文件当中来对拦截器对象进行注册操作
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="default-package" abstract="/" extends="struts-default"> <!--进行拦截器的注册操作--> <interceptors> <interceptor name="MyIntercept" class="com.intercept.MyIntercept"> <!--指定当前方法拦截器对象要进行拦截的方法对象--> <param name="includeMethods">doFirst,doSecond</param> <!-- 指定对doThird方法不进行过滤操作 --> <!-- <param name="excludeMethods">doThird</param> --> </interceptor> <!--进行一个拦截器栈的注册操作--> <interceptor-stack name="MyInterceptStack"> <interceptor-ref name="MyIntercept"/> <interceptor-ref name="defaultStack"/> </interceptor-stack> </interceptors> <action name="SomeAction_*" class="com.action.SomeAction" method="{1}"> <result name="success">/success.jsp</result> <!--将自定义的拦截器栈于someAction对象进行绑定操作,当对SomeAction对象进行访问操作时,将会触发该拦截器对象--> <interceptor-ref name="MyInterceptStack"/> </action> </package> </struts>