Sample login verification code generated by JSP + Servlet, servlet Verification Code

Source: Internet
Author: User

Sample login verification code generated by JSP + Servlet, servlet Verification Code

A four-digit verification code is randomly generated, including Chinese characters, numbers, and uppercase/lowercase letters.

1. Servlet class

Package servlet; import java. awt. basicStroke; import java. awt. color; import java. awt. font; import java. awt. graphics; import java. awt. graphics2D; import java. awt. geom. affineTransform; import java. awt. geom. line2D; import java. awt. image. bufferedImage; import java. io. IOException; import java. io. printWriter; import java. util. random; import javax. imageio. imageIO; import javax. servlet. servletException; import javax. ser Vlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import javax. servlet. http. httpSession; public class PictureCheckCode extends HttpServlet {private static final long serialVersionUID = 1L; public PictureCheckCode () {super ();} public void destroy () {super. destroy ();} public void init () throws ServletException {super. init ();}/* This method The main function is to obtain the Random Color */public Color getRandColor (int s, int e) {random Random = new Random (); if (s> 255) s = 255; if (e> 255) e = 255; int r, g, B; r = s + random. nextInt (e-s); // randomly generates the R Value g = s + random in the RGB color. nextInt (e-s); // randomly generates the g value B = s + random in the RGB color. nextInt (e-s); // returns new Color (r, g, B) in the random RGB Color;} public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {Syst Em. out. println ("this is doGet method"); this. doPost (request, response);} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// set the response of images not cached. setHeader ("Pragma", "No-cache"); response. setHeader ("Cache-Control", "No-cache"); response. setDateHeader ("Expires", 0); // specify the generated response image. This statement must not be missing; otherwise, it is incorrect. response. setContentType ("image/jpeg"); int Width = 80, height = 35; // specify the width and height of the Verification Code. BufferedImage image = new BufferedImage (width, height, BufferedImage. TYPE_INT_RGB); // creates a BufferedImage object, which is equivalent to an image Graphics g = image. getGraphics (); // create a Graphics object, which is equivalent to the brush Graphics2D g2d = (Graphics2D) g; // create a Grapchics2D object Random random = new Random (); font mfont = new Font ("", Font. BOLD, 16); // defines the font style g. setColor (getRandColor (200,250); g. fillRect (0, 0, width, height); // draw back Jing g. setFont (mfont); // set the font g. setColor (getRandColor (180,200); // draw 100 lines of random color and position. The line is 2f for (int I = 0; I <100; I ++) {int x = random. nextInt (width-1); int y = random. nextInt (height-1); int x1 = random. nextInt (6) + 1; int y1 = random. nextInt (12) + 1; BasicStroke bs = new BasicStroke (2f, BasicStroke. CAP_BUTT, BasicStroke. JOIN_BEVEL); // customizes the line style Line2D line = new Line2D. double (x, y, x + x1, y + y1); g2d. setStroke (bs); g2d. draw (Line); // draw a straight line} // The output consists of English letters, numbers, and Chinese characters. The specific combination method is determined based on the random number generated. String sRand = ""; String ctmp = ""; int itmp = 0; // set the output verification code to four-digit for (int I = 0; I <4; I ++) {switch (random. nextInt (3) {case 1: // generate the A-Z letter itmp = random. nextInt (26) + 65; ctmp = String. valueOf (char) itmp); break; case 2: // generate String [] rBase = {"0", "1", "2", "3 ", "4", "5", "6", "7", "8", "9", "a", "B", "c", "d ", "e", "f"}; // generate the first partition code int r1 = random. nextInt (3) + 11; String str_r1 = rBase [r1]; // generates the second-bit code int r2; if (r1 = 13) {r2 = random. nextInt (7);} else {r2 = random. nextInt (16);} String str_r2 = rBase [r2]; // generate the first bit code int r3 = random. nextInt (6) + 10; String str_r3 = rBase [r3]; // generates the second bit code int r4; if (r3 = 10) {r4 = random. nextInt (15) + 1;} else if (r3 = 15) {r4 = random. nextInt (15);} else {r4 = random. nextInt (16);} String str_r4 = rBase [r4]; // convert the generated inner code to byte [] bytes = new byte [2]; // Save the generated code to the first element of the byte array. String str_12 = str_r1 + str_r2; int tempLow = Integer. parseInt (str_12, 16); bytes [0] = (byte) tempLow; // Save the generated bit code to the second element of the byte array String str_34 = str_r3 + str_r4; int tempHigh = Integer. parseInt (str_34, 16); bytes [1] = (byte) tempHigh; ctmp = new String (bytes); break; default: itmp = random. nextInt (10) + 48; ctmp = String. valueOf (char) itmp); break;} sRand + = ctmp; Color color = new Color (20 + random. nextInt (110), 20 + random. nextInt (110), random. nextInt (110); g. setColor (color); // randomly scales and rotates the generated random number to specify the angle. we recommend that you do not scale or rotate the text, because the image may not be properly displayed/* rotate the text to specify the angle */Graphics2D g2d_word = (Graphics2D) g; affineTransform trans = new AffineTransform (); trans. rotate (45) * 3.14/180,15 * I + 8, 7);/* zoom text */float scaleSize = random. nextFloat () + 0.8f; if (scaleSize> 1f) scaleSize = 1f; trans. scale (scaleSize, scaleSize); g2d_word.setTransform (trans); g. drawString (ctmp, 15 * I + 18, 14);} HttpSession session = request. getSession (true); session. setAttribute ("randCheckCode", sRand); System. out. println (sRand); g. dispose (); // release the system resource ImageIO occupied by g. write (image, "JPEG", response. getOutputStream (); // output image }}

2. web. xml configuration

<servlet>  <description>This is the description of my J2EE component</description>  <display-name>This is the display name of my J2EE component</display-name>  <servlet-name>PictureCheckCode</servlet-name>  <servlet-class>servlet.PictureCheckCode</servlet-class> </servlet><servlet-mapping>  <servlet-name>PictureCheckCode</servlet-name>  <url-pattern>/pictureCheckCode</url-pattern> </servlet-mapping>

3. jsp page output verification code

<% @ Page language = "java" import = "java. util. *" pageEncoding = "UTF-8" %> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> 

4. Check whether the verification code is consistent with that entered by the backend Servlet.

Use request. getParameter ("checkCode") to obtain the entered verification code, which is consistent with session. getAttribute ("randCheckCode.

Public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String code = request. getParameter ("checkCode"); HttpSession session = request. getSession (); if (! Code. equals (session. getAttribute ("randCheckCode") {request. setAttribute ("errormsg", "Incorrect verification code");} System. out. println (request. getAttribute ("errormsg "));}

Running result:


The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

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.