Java – using filter and session to prevent page from repeatedly submitting

Time:2020-2-12

Java – using filter and session to prevent page from repeatedly submitting
Solution:
1 when users visit the form page, they go through the filter first. The filter sets a random ID as the token token, and puts the token into the hidden field of the form
2. The form responds to the browser, and the user fills in the data and submits the request;
3. The request passes through the filter. The filter obtains the token in the form for verification. If it is consistent with the token generated before, the request will be released and the token will be cleared;
If the user submits the form repeatedly, the request is verified by the filter and filter. Because the token has been cleared and invalid after the first release, the token is inconsistent and does not release. Jump to the reminder interface

Required knowledge:
1 filter Basics
2 servlet Basics
3 filter Basics
4. JSP Basics

code implementation

Form form page implemented by JSP

Insert title here


	
		
		
		
		
		User name:
		Password:

  

2 filter

 

package com.woniu.filter.controler;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class TokenFilte
 */

//Filter all servlets
@WebFilter("*")

public class TokenFilte implements Filter {

  
    public TokenFilte() {
        // TODO Auto-generated constructor stub
    }

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		//Set encoding set
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charser=utr-8");
		//Downward transformation
		HttpServletRequest req=(HttpServletRequest) request;
		HttpServletResponse resp=(HttpServletResponse) response;
		
		//Get token of form
		String parameterToken = req.getParameter("token");
		//Get token in session
		String sessionToken = (String) req.getSession().getAttribute("token");
		
		//To determine the token of the form, if it is not empty, it means that the user has submitted the form, and it needs to verify whether the form is submitted repeatedly,
		//If it is blank, it is the first time to enter the login page, and token needs to be set
		if (parameterToken!=null) {
			//Judge whether two tokens are equal, release if they are equal, and reset the token
			if(parameterToken.equals(sessionToken)) {
				//Reset token
				req.getSession().removeAttribute("token");
				chain.doFilter(request, response);
			}Else {// indicates repeated submission and forwarding to the prompt page
				req.getRequestDispatcher("repeatReminder").forward(request, response);
				
			}
		}Else {// the first time you come in, you need to set a token
			//Generate universe unique code
			String token = UUID.randomUUID().toString();
			//Set session
			req.getSession().setAttribute("token",token);
			// release
			chain.doFilter(request, response);
		}
	
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}

  

3 servlet for form response
Use thread to sleep for 30 seconds to simulate network congestion

package com.woniu.filter.controler;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class PrintUser
 */
@WebServlet("/login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			//Thread sleep for 30 seconds, easy to demonstrate network congestion
			Thread.sleep(30000);
			Response. Getwriter(). Write ("login succeeded");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

  

4 servlet that responds on repeat commit
Jump to the reminder page when submitting repeatedly

package com.woniu.filter.controler;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class repeatReminder
 */
@WebServlet("/repeatReminder")
public class repeatReminder extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public repeatReminder() {
        super();
        // TODO Auto-generated constructor stub
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Response. Getwriter(). Write ("the page is processing, please do not submit repeatedly");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

  

Recommended Today

Learning record of mongodb Master Course (day 16)

Sixteenth days The chapter to be learned is 19 transaction development: write operation transaction. In fact, it mainly talks about a parameter writeconcert. What is writeconcert? As we learned in the first chapter before, mongodb in the production environment also needs a 3-node cluster at least. Then writeconert is used to control how many nodes […]