欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

《struts---利用Token防止表单重复提交》

程序员文章站 2022-07-02 23:45:26
...
/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package com.fenghuo.struts.web.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/** 
 * MyEclipse Struts
 * Creation date: 10-07-2012
 * 
 * XDoclet definition:
 * @struts.action validate="true"
 * @struts.action-forward name="success" path="/WEB-INF/jsp/register.jsp"
 */
public class UserRegUI extends Action {
	/*
	 * Generated Methods
	 */

	/** 
	 * 转到注册页面的action
	 * Method execute
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		//在进入注册页面时为表单生产一个隐藏的标签,储存Token的值
		this.saveToken(request);
		
		return mapping.findForward("success");
	}
}
/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package com.fenghuo.struts.web.actions;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.fenghuo.struts.web.forms.UserForm;

/** 
 * MyEclipse Struts
 * Creation date: 10-07-2012
 * 
 * XDoclet definition:
 * @struts.action path="/UserRegister" name="userForm" scope="request" validate="true"
 * @struts.action-forward name="main.jsp" path="/WEB-INF/jsp/main.jsp" redirect="true"
 */
public class UserMain extends Action {
	/*
	 * Generated Methods
	 */

	/** 
	 * 用户点击提交后会将信息提交到此action
	 * Method execute
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		ActionMessages errors = new ActionMessages();	
		
		//判断如果Token的值不存在,说明重复提交。
		//重复提交,只是用户在当前页面多次点击提交按钮,或后退重新提交
		//如果用户刷新,就会生产新的表单和Token也就不会重复提交了
		if(!isTokenValid(request))
		{
			//添加重复提交信息,并在注册页面做相应的操作,让信息显示出来即可
			errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("表单重复提交!",false));
		}
		if(!errors.isEmpty())
		{
			saveErrors(request, errors);
			//跳转到错误页面
			return mapping.getInputForward();
		}
		//如果上面未跳转,则清除Token
		resetToken(request);
		
		return mapping.findForward("success");
	}
}
《struts---利用Token防止表单重复提交》