博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
struts2 拦截器_Struts2令牌拦截器示例
阅读量:2534 次
发布时间:2019-05-11

本文共 10346 字,大约阅读时间需要 34 分钟。

struts2 拦截器

Struts 2 token interceptor can be used to handle multiple form submission problem. While designing web application, sometimes we have to make sure that double form submission is treated as duplicate request and not be processed. For example, if user reloads the online payment form and there are not enough checks in place to identify it as duplicate request, customer will be charged twice.

Struts 2令牌拦截器可用于处理多种表单提交问题。 在设计Web应用程序时,有时我们必须确保将重复提交的表单视为重复请求,而不进行处理。 例如,如果用户重新加载在线付款表单,但是没有足够的支票将其识别为重复请求,则将向客户收取两次费用。

Double form submission problem handling needs to be done both at client side and server side. In client side, we can disable the submit button, disable back button but there will always be options through which user can send the form data again. Struts2 provides token interceptors that are designed to deal with this particular problem.

双重表单提交问题处理需要同时在客户端和服务器端进行。 在客户端,我们可以禁用“提交”按钮,“禁用”后退按钮,但是总会有一些选项,用户可以通过这些选项再次发送表单数据。 Struts2提供了旨在解决此特定问题的令牌拦截器。

Struts2令牌拦截器 (Struts2 Token Interceptor)

There are two interceptors defined in struts-default package as:

struts-default软件包中定义了两个拦截器,它们是:

These interceptors are not part of any predefined interceptor stack because if we add it for any action, the form submitted should have a token parameter else it will throw exception. We will look it’s usage with a simple project. Final project structure will look like below image.

这些拦截器不属于任何预定义的拦截器堆栈,因为如果我们将其添加到任何操作中,则提交的表单应具有token参数,否则它将引发异常。 我们将在一个简单的项目中查看它的用法。 最终的项目结构如下图所示。

Struts2令牌拦截器示例配置文件 (Struts2 Token Interceptor Example Configuration Files)

web.xml

web.xml

Struts2TokenInterceptor
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*

Deployment descriptor is configured to use Struts 2 framework.

部署描述符被配置为使用Struts 2框架。

pom.xml

pom.xml

4.0.0
Struts2TokenInterceptor
Struts2TokenInterceptor
0.0.1-SNAPSHOT
war
maven-compiler-plugin
3.1
1.6
1.6
maven-war-plugin
2.3
WebContent
false
${project.artifactId}
org.apache.struts
struts2-core
2.3.15.1

The web application is configured as maven project where we have added struts2-core dependency.

该Web应用程序被配置为maven项目,在其中添加了struts2-core依赖项。

struts.xml

struts.xml

/update.jsp
/update_success.jsp
/update.jsp
/invalid_token.jsp
  1. We can use either token interceptor or tokenSession interceptor with any action.

    我们可以对任何动作使用token拦截器或token tokenSession拦截器。
  2. If token interceptor identifies the request as duplicate, then it returns the result invalid.token, that’s why we have a result configured for this.

    如果token拦截器将请求标识为重复请求,则它将返回结果invalid.token,这就是我们为此配置结果的原因。
  3. If form field validation fails then input result is returned where we are returning the same page from where we get the request.

    如果表单字段验证失败,那么将在我们返回请求的同一页面上返回输入结果。

We will look into the complete flow once we have seen the implementation and application behavior with duplicate request.

一旦看到重复请求的实现和应用程序行为,我们将研究完整的流程。

Struts2令牌拦截器示例操作类 (Struts2 Token Interceptor Example Action Class)

UpdateUserAction.java

UpdateUserAction.java

package com.journaldev.struts2.actions;import java.util.Date;import com.opensymphony.xwork2.ActionSupport;public class UpdateUserAction extends ActionSupport {	@Override	public String execute() {		System.out.println("Update Request Arrived to Action Class");		//setting update time in action class		setUpdateTime(new Date());		return SUCCESS;	}	@Override	public void validate(){		if(isEmpty(getName())){			addActionError("Name can't be empty");		}		if(isEmpty(getAddress())){			addActionError("Address can't be empty");		}	}	//java bean variables	private String name;	private String address;	private Date updateTime;	public String getName() {		return name;	}	public void setName(String name) {		this.name = name;	}	public String getAddress() {		return address;	}	public void setAddress(String address) {		this.address = address;	}	public Date getUpdateTime() {		return updateTime;	}	public void setUpdateTime(Date updateTime) {		this.updateTime = updateTime;	}	private boolean isEmpty(String str) {		return str == null ? true:(str.equals("") ? true:false);	}}

A simple action class with basic form fields validation and some java bean properties. Notice that update time is set by action class, it has been added to show the application behavior when we use tokenSession interceptor.

一个具有基本表单域验证和一些Java bean属性的简单操作类。 请注意,更新时间是由操作类设置的,已添加它以显示当我们使用tokenSession拦截器时的应用程序行为。

Struts2令牌拦截器示例JSP页面 (Struts2 Token Interceptor Example JSP Pages)

update.jsp

update.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"    pageEncoding="US-ASCII"%><%@ taglib uri="/struts-tags" prefix="s" %>
Update User Request Page
<%-- add token to JSP to be used by Token interceptor --%>

The entry point of the application from where user will submit form to update some information. We are using actionerror tag to show any validation errors added by the application. The most important point to note is s:token tag that will be used by token interceptors in making sure duplicate requests are not getting processed.

用户从此处提交表单以更新某些信息的应用程序的入口点。 我们正在使用actionerror标记来显示应用程序添加的任何验证错误。 要注意的最重要的一点是s:token标记,令牌拦截器将使用s:token标记来确保未处理重复的请求。

update_success.jsp

update_success.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"    pageEncoding="US-ASCII"%><%@ taglib uri="/struts-tags" prefix="s" %>
Update User Success Page

User information updated successfully.

Name:
Address:
Update Time:

Thank You!

Simple JSP page showing action class java bean properties.

简单的JSP页面显示了操作类Java bean属性。

invalid_token.jsp

invalid_token.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"    pageEncoding="US-ASCII"%><%@ taglib uri="/struts-tags" prefix="s" %>
Update Duplicate Request Page

User information is not updated, duplicate request detected.

Possible Reasons are:

  • Back button usage to submit form again
  • Double click on Submit button
  • Using "Reload" Option in browser

Simple showing different methods that can cause multiple form submissions, notice the usage.

简单的显示了可能导致提交多个表单的不同方法,请注意用法。

Now when we will run our application, we will see following pages as response in the same order.

现在,当我们运行应用程序时,我们将以相同的顺序看到以下页面作为响应。

If you will look into the source of input page, you will see that Struts2 API has converted token tag to following HTML snippet.

如果您查看输入页面的源,您将看到Struts2 API已将令牌标记转换为以下HTML代码段。

Also you will notice following logs snippet.

您还会注意到以下日志片段。

Update Request Arrived to Action ClassWARNING: Form token HGWQI7ZGP7KFGJLDPNTSFHLUX5RF26IK does not match the session token null.

Notice that duplicate request doesn’t even reach to action class and token interceptor returns the invalid.token page as response.

请注意,重复请求甚至没有到达动作类,并且令牌拦截器返回invalid.token页面作为响应。

If you will use tokenSession interceptor, you will notice that it returns the same response as the first request. You can confirm this by going back and edit form fields and then submitting form again. The response update time and field values will be old values as sent in the first request.

如果您将使用tokenSession拦截器,则会注意到它返回的响应与第一个请求相同。 您可以通过返回并编辑表单字段,然后再次提交表单来确认。 响应更新时间和字段值将是在第一个请求中发送的旧值。

Struts2令牌拦截器如何工作 (How Struts2 Token Interceptor Works)

Now let’s see how token interceptor works to handle multiple form submissions.

现在,让我们看看令牌拦截器如何处理多种表单提交。

  1. When a request is made to the update action, Struts2 tags API generates a unique token and set it to the session. The same token is sent in the HTML response as hidden field.

    当请求更新操作时,Struts2标签API会生成一个唯一令牌并将其设置为会话。 在HTML响应中将相同的令牌作为隐藏字段发送。
  2. When the form is submitted with token, it is intercepted by token interceptor where it tries to fetch the token from the session and validate that it’s same as the token received in the request form. If token is found in session and validated then the request is forwarded to the next interceptor in the chain. Token interceptor also removes the token from the session.

    当表单与令牌一起提交时,它会被令牌拦截器拦截,在此尝试从会话中获取令牌并验证其是否与请求表单中接收的令牌相同。 如果在会话中找到令牌并对其进行了验证,则该请求将转发到链中的下一个拦截器。 令牌拦截器还会从会话中删除令牌。
  3. When the same form is submitted again, token interceptor will not find it in the session. So it will add an action error message and return invalid.token result as response. You can see this message in above image for invalid_token.jsp response. This way token interceptor make sure that a form with token is processed only once by the action.

    当再次提交相同的表单时,令牌拦截器将在会话中找不到它。 因此,它将添加操作错误消息并返回invalid.token结果作为响应。 您可以在上图中看到此消息,以获取invalid_token.jsp响应。 这样,令牌拦截器可确保带有令牌的表单仅被该操作处理一次。
  4. If we use tokenSession interceptor, rather than returning invalid token response, it tries to return the same response as the returned by the first action with same token. This implementation is done in the TokenSessionStoreInterceptor class that saves the response for each token in the session.

    如果我们使用tokenSession拦截器,而不是返回无效的令牌响应,它将尝试返回与第一个具有相同令牌的操作所返回的响应相同的响应。 此实现是在TokenSessionStoreInterceptor类中完成的,该类保存会话中每个令牌的响应。
  5. We can override the action error message sent by token interceptor through i18n support with key as “struts.messages.invalid.token”.

    我们可以使用i18n支持覆盖令牌拦截器通过i18n支持发送的操作错误消息,密钥为“ struts.messages.invalid.token”。

Thats all for the usage of Struts2 token interceptor to handle multiple form submission problem in web application. Download the application from below link and play around with it for better understanding.

多数民众赞成使用Struts2令牌拦截器来处理Web应用程序中的多种表单提交问题。 从下面的链接下载该应用程序,并进行试用以更好地理解。

翻译自:

struts2 拦截器

转载地址:http://lvlzd.baihongyu.com/

你可能感兴趣的文章
微软自己的官网介绍 SSL 参数相关
查看>>
Composite UI Application Block (CAB) 概念和术语
查看>>
ajax跨域,携带cookie
查看>>
阶段3 2.Spring_01.Spring框架简介_03.spring概述
查看>>
阶段3 2.Spring_02.程序间耦合_1 编写jdbc的工程代码用于分析程序的耦合
查看>>
阶段3 2.Spring_01.Spring框架简介_04.spring发展历程
查看>>
阶段3 2.Spring_02.程序间耦合_3 程序的耦合和解耦的思路分析1
查看>>
阶段3 2.Spring_02.程序间耦合_5 编写工厂类和配置文件
查看>>
阶段3 2.Spring_01.Spring框架简介_05.spring的优势
查看>>
阶段3 2.Spring_02.程序间耦合_7 分析工厂模式中的问题并改造
查看>>
阶段3 2.Spring_02.程序间耦合_4 曾经代码中的问题分析
查看>>
阶段3 2.Spring_03.Spring的 IOC 和 DI_2 spring中的Ioc前期准备
查看>>
阶段3 2.Spring_03.Spring的 IOC 和 DI_4 ApplicationContext的三个实现类
查看>>
阶段3 2.Spring_02.程序间耦合_8 工厂模式解耦的升级版
查看>>
阶段3 2.Spring_03.Spring的 IOC 和 DI_6 spring中bean的细节之三种创建Bean对象的方式
查看>>
阶段3 2.Spring_04.Spring的常用注解_3 用于创建的Component注解
查看>>
阶段3 2.Spring_04.Spring的常用注解_2 常用IOC注解按照作用分类
查看>>
阶段3 2.Spring_09.JdbcTemplate的基本使用_5 JdbcTemplate在spring的ioc中使用
查看>>
阶段3 3.SpringMVC·_07.SSM整合案例_02.ssm整合之搭建环境
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第1节零基础快速入门SpringBoot2.0_3、快速创建SpringBoot应用之手工创建web应用...
查看>>