---
title: "Struts2使用之拦截器实例"
author: "netxdiy"
date: "2011-03-21T11:16:09Z"
tags: ["JSP", "Struts", "XML"]
categories: ["企业架构"]
slug: "struts2"
draft: false
lastmod: "2011-03-21T16:14:13Z"
id: 969078
url: "https://netxdiy.iteye.com/blog/969078"
---

实例一：防止表单重复提交 防止重复提交：有两种方法：一是使用token拦截器，二是使用tokenSession 第一种方法步骤： 1、 先在页面中放一个令牌。调用Struts标签，服务器自动分派。 2、 在struts.xml文件定义token拦截器。 3、 在struts.xml文件配置有重复提交的错误页面，即： /repeatSubmitError.jsp 第二种方法基本与第一种方法基本相同，只不用配置重复提交的错误页面，如果发生重复提交，返回success。 实例二：PreResultInteceptor 这个功能是在Action返回到result时执行。 拦截器 --&gt; Action --&gt; Result --&gt; 拦截器 实现步骤： 1、 定义一个类实现PreResultListener接口，实现beforeResult方法 public class TestPreResultInteceptor implements PreResultListener { public void beforeResult(ActionInvocation arg0, String arg1) { System.out.println("在结果集返回之前执行了beforeResult方法"); } } 2、 自定义一个拦截器与上面定义类进行绑定。 public class TestInterceptor extends AbstractInterceptor { @Override public String intercept(ActionInvocation invocation) throws Exception { invocation.addPreResultListener(new TestPreResultInteceptor()); System.out.println("在action执行execute方法之前执行进行拦截"); String result = invocation.invoke(); System.out.println("在action执行execute方法之后执行进行拦截"); return result; } }