Repeated submission of servlet processing forms and use Referer anti-Leech and to implement request inclusion pages

Source: Internet
Author: User

Let's talk to the code. I have integrated these three items into a web project.


The first is Web. xml.

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5"xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><servlet><servlet-name>FormServlet</servlet-name><servlet-class>com.jadyer.servlet.FormServlet</servlet-class></servlet><servlet-mapping><servlet-name>FormServlet</servlet-name><url-pattern>/servlet/FormServlet</url-pattern></servlet-mapping><welcome-file-list><welcome-file>form.jsp</welcome-file></welcome-file-list></web-app>

Then form page form. jsp

<% @ Page Language = "Java" pageencoding = "UTF-8" %> <% @ page import = "com. jadyer. util. datacoderutil "%> <% // generate the form token session. setattribute ("mytoken", datacoderutil. generatetoken (); // request contains the page: You can also use this method to include the page. // request. getrequestdispatcher ("/form. JSP "). include (request, response); %> <form action = "<% = request. getcontextpath () %>/servlet/formservlet "method =" Post "> <input type =" hidden "name =" mytoken "value =" $ {mytoken} "> User: <input type = "text" name = "username"> <br/> password: <input type = "password" name = "password"> <br/> <input type = "Submit" value = "Submit"> </form>

The following is the tool class datacoderutil. java used to generate form tokens.

Package COM. jadyer. util; import Java. security. messagedigest; import Java. security. nosuchalgorithmexception; import Java. util. random; import sun. misc. base64encoder; /*** datacoderutil * @ see ================================== ========================================================== =====================* @ see generatetoken () is the form token generator created when processing repeated forms for submission, it returns the string * @ see ============================== encrypted by MD5 and base64. ================================ ========================================================== = * @ See every data in Java has a summary, data fingerprint. No matter how big the data is, its fingerprint is fixed with 128 bits, that is, 16 bytes * @ see. We can use Java. security. messagedigest tool class to obtain the data summary of random numbers, that is, the data fingerprint * @ see ======================================== ========================================================== =================* @ see all-new algorithm: base64 encoding * @ see any data encoded by the base64 algorithm will return a plaintext string. This algorithm has one feature: It sets every three bytes, all are changed to four bytes * @ see. For example, 00110010.11001101.00101001 will be changed to 20171100.00101100.00110100.00101001 * @ see, which means to divide the original 24bit into four equal parts, and then add two zeros in each, to make it a 32bit, that is, four bytes * @ see. Therefore, the minimum value of each byte is 00000000, and the maximum value is 00111111, that is, the minimum value is zero, the maximum value is 63 * @ see. Therefore, after base64 algorithm encoding, the maximum value of each byte will not exceed 64 * @ see. Finally, the base64 algorithm will query its own custom code table, this code table records the plaintext characters on the keyboard corresponding to 0--63, finally, return * @ see ====================================== ========================================================== ===================* @ author macro Yu * @ create Mar 6, 2012 2:38:04 am */public class datacoderutil {public static string generatetoken () {string mytoken = system. currenttimemillis () + new random (). nextint () + ""; try {byte [] mytokenmd5 = messagedigest. getinstance ("MD5 "). digest (mytoken. getbytes (); // MD5 Algorithm to encrypt return New base64encoder (). encode (mytokenmd5); // base64 encryption algorithm, and finally return} catch (nosuchalgorithmexception e) {Throw new runtimeexception (E );}}}

Finally, formservlet. Java is used to process form requests.

Package COM. jadyer. servlet; import Java. io. ioexception; import javax. servlet. servletexception; import javax. servlet. HTTP. httpservlet; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; public class formservlet extends httpservlet {Private Static final long serialversionuid =-34351_674549645942l; Public void dopost (httpservletrequest request, httpservletresponse Response) throws servletexception, ioexception {/*** when using the Referer anti-leech * @ see client access, only the URL headed by http: // 127.0.0.1 */string Referer = request can be recognized. getheader ("Referer"); If (null = Referer |! Referer. startswith ("http: // 127.0.0.1") {response. sendredirect ("/index. JSP "); return; // if this line of code is not available, the following code will still be executed after redirection}/*** judge that the form is submitted repeatedly * @ see: see my another article http://blog.csdn.net/jadyer/article/details/6174095 */If (! Istokenvalid (request, response) {system. out. println ("Please do not submit the form again... "); return;} request. getsession (). removeattribute ("mytoken"); system. out. println ("register a user in the database... ");}/*** determine whether the form token is valid */private Boolean istokenvalid (httpservletrequest request, httpservletresponse response) {string client_token = request. getparameter ("mytoken"); string server_token = (string) request. getsession (). getattribute ("mytoken"); If (NUL L = client_token) {return false;} If (null = server_token) {return false;} If (! Client_token.equals (server_token) {return false;} return true ;}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.