[JSP] Solution to prevent duplicate page form

Personal notes, write convenience later.

When we write the registration page, the user completes the registration, submits the registered user information, and inputs to save the database. Most reluctance to appear at a session is the result of multiple introductions. Incidents like this happen.

1. Set a tag for each request. When this page is the first time, it is requested for the first time.

2. When the form is submitted, go to the page to process marks in the application.

(TokenGen.java)

package com.beans;

import java.util.*;
import javax.servlet.http.*;

public class TokenGen {
	private static TokenGen instance = new TokenGen();

	private TokenGen() {}

	public static TokenGen getInstance() {
		return instance;
	}

	public synchronized boolean isTokenValid(HttpServletRequest request) {
		// нет заседания, судить незаконно
		HttpSession session = request.getSession(false); 
		if (session == null)
			return false;

		 // сеанс не содержит токен,
                 // объяснить, что после подачи, переселение () очистите токен
                 // Судя по нелегальному
		String stoken = (String) session.getAttribute("token"); 
		if (stoken == null)
			return false;

		 // Параметры запроса запроса не содержат токена,
                 // Судя по нелегальному
		String rtoken = request.getParameter("token");
		if (rtoken == null)
			return false;

		 // Токены в запросе на запрос и токены, сохраненные на сессии, считаются незаконными
		return stoken.equals(rtoken);
	}
	
    /*
           * Re -set token, когда страница запрашивается, удалите атрибут токена в сеансе
     */
	public synchronized void resetToken(HttpServletRequest request)
	{
		HttpSession session = request.getSession(false);
		if (session!=null)
		{
			session.removeAttribute("token");
		}
	}
	/*
	  * Чтобы запросить новую марку токена, этот знак формируется случайным двойным номером, а значение символа сохраняется в сеансе
	 */
	
	public synchronized void saveToken(HttpServletRequest request)
	{
		HttpSession session = request.getSession(true);
		Random rand = new Random();
		Double d = rand.nextDouble();
		session.setAttribute("token", d.toString());	
	}
}

(Form.jsp) среди них

<%@ page language="java" import="com.beans.*" pageEncoding="gb2312"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>

     <Title> Регистрация страница 1 </title>

  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="This is my page">
 </head>
 <%
  TokenGen.getInstance().saveToken(request);
  String s = (String)session.getAttribute("token"); 
 %>
 <body>
  <form id="form1" name="form1" method="post" action="register.jsp">
  
   <table align="center">
   <tr>
    <td colspan="2"><br><input type="hidden" name="token" value="<%=s%>"/>
    </td>
   </tr>
    <tr>
     <td align="right">
             имя пользователя: 
     </td>
     <td>
      <input type="text" name="t1" />
     </td>
    </tr>

    <tr>
     <td align="right">
             пароль: 
     </td>
     <td>
      <input type="password" name="t2" />
     </td>
    </tr>

    <tr>
     <td align="right">
             Подтвердите пароль: 
     </td>
     <td>
      <input type="password" name="t3" />
     </td>
    </tr>

    <tr>
     <td align="right">
             Пол: 
     </td>
     <td>
      <input type="radio" name="radio" id="radio" value="boy" />
             мужчина 
      <input type="radio" name="radio" id="radio2" value="gril" />
             Женский 
     </td>
    </tr>

    <tr>
     <td align="right">
             личное заявление: 
     </td>
     <td>
      <textarea name="textraea1" rows="15" cols="60"></textarea>
     </td>
    </tr>

    <tr>
     <td align="right">
             <input type = "Отправить" name = "кнопка" id = "кнопка" value = "pospent" />
     </td>
     <td>
             <input type = "сбросить" name = "button2" id = "button2" value = "сброс" />
     </td>
    </tr>
   </table>
  </form>
 </body>
</html>

(Register.jsp) Processing the request

<%@ page language="java" import="com.beans.*" pageEncoding="gb2312"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>

    
         <Title> Обработка регистрации страница 1 </title>
    
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">    
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->

  </head>
  
  <body>
   <%
    TokenGen tokenGen=TokenGen.getInstance();
    if (!tokenGen.isTokenValid(request))
    {
           out.print («Это повторяемое представление или незаконное представление!»);
    }
    else
    {
           // обрабатывать запрос и выполнить метод переселения, чтобы удалить токен в сеансе
     tokenGen.resetToken(request);
    }
    
    %>
  </body>
</html>

The other is to limit re-submissions by setting time intervals. The principle is similar to the above.

Reprinted at: https://www.cnblogs.com/jarl/p/5893009.html

Leave a Comment