struts2自己定义拦截器


首先是struts2框架中基本的两个文件:一个是拦截器类,另外一个是struts.xml配置文件。

简单来说,一个是说明要做的事,一个是说明在哪里做的。

拦截器类

package com.test.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class TestInterceptor extends AbstractInterceptor{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		System.out.println("拦截器之前。。

。。。。。。。。"); String result=invocation.invoke(); System.out.println("。。

。。。。。。。。

拦截器之后。

"); return result; } }


这个拦截器很easy,就是在全部动作之前和之后输出两段话。

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>

  	<constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.devMode" value="true" /> 

    <package name="default" namespace="" extends="struts-default">
        <!-- 这里是拦截器的配置 -->
        <interceptors>
            <interceptor name="test" class="com.test.interceptor.TestInterceptor">  
            </interceptor>  
             <interceptor-stack name="myStack">
                 <interceptor-ref name="test"/>
                 <interceptor-ref name="defaultStack"/>
             </interceptor-stack>
        </interceptors>
    	<!-- 正确和错误的分别跳转。input是在验证失败后会跳转的页面 -->
    	<action name="data" class="com.test.action.ValideAction">
    	    <interceptor-ref name="myStack"></interceptor-ref> <!-- 使用拦截器的动作 -->
    	     <result name="success">/result.jsp</result>
    	    <result name="input">/login.jsp</result>
    	</action>
    </package>
</struts>

输出结果



posted @ 2016-03-16 12:39  mengfanrong  阅读(186)  评论(0编辑  收藏  举报