Generate a Servlet-like CSDN dynamic verification code-with numbers and letters, servletcsdn

Source: Internet
Author: User

Generate a Servlet-like CSDN dynamic verification code-with numbers and letters, servletcsdn

Original works of Lin bingwen Evankaka. Reprinted please indicate the source http://blog.csdn.net/evankaka

I. Implementation ideas:

(1) first, create a Servlet. The Servlet returns an image to the client through a byte response. The image is generated by using the Java 2D class library in JDK. The image is generated by a random number and then written into the image format. At last, the random string is kept in the Session state for comparison after the user fills in.
(2) On the JSP page that requires the verification code, use to introduce the image.

(3) Submit the verification code to a Servlet. In this Servlet, request. the getParameter () method is used to obtain the user-added verification code. Then, the obtained verification code is compared with the verification code generated in the Session. If the comparison is successful, the verification code is passed, otherwise, a message indicating a verification code error is returned.

(4) If you want to copy the dynamic CSDN verification code, you need to generate numbers and symbols (+,-, *), calculate Chinese Characters Based on symbols, calculation results, store the results in a List <String>.

Let's take a look at the effect:



Ii. Code

1. Overall project structure


2. generate code with numbers and Images

AuthCode. java

Package com. mucfc; import java. awt. color; import java. awt. graphics; import java. awt. font; import java. awt. image. bufferedImage; import java. util. random;/*** generate Verification Code image * @ author Lin bingwen Evankaka (blog: http://blog.csdn.net/evankaka) * @ since 2015.6.22 */public class AuthCode {public static final int AUTHCODE_LENGTH = 5; // The verification code length is public static final int SINGLECODE_WIDTH = 15; // The width of a single verification code is public static final int SINGLECODE_HEIGHT = 30; // the height of a single verification code is public static final int SINGLECODE_GAP = 4; // The interval between a single verification code is public static final int IMG_WIDTH = AUTHCODE_LENGTH * (SINGLECODE_WIDTH + SINGLECODE_GAP); public static final int IMG_HEIGHT = SINGLECODE_HEIGHT; public static final char [] CHARS = {'0', '1', '2', '3', '4', '5', '6 ', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G ', 'H', 'I', 'J', 'k', 'l', 'M', 'n', 'O', 'P', 'Q ', 'R', 's', 't', 'U', 'V', 'w', 'x', 'y', 'z', 'A ', 'B', 'C', 'D', 'E', 'F', 'G', 'h', 'I', 'J', 'k ', 'l', 'M', 'n', 'O', 'P', 'Q', 'R', 's', 't', 'U ', 'V', 'w', 'x', 'y', 'z'}; static Random random = new Random (); /*** return the number * @ return String */public static String getAuthCode () {StringBuffer buffer = new StringBuffer (); for (int I = 0; I <5; I ++) {// generate 6-character buffer. append (CHARS [random. nextInt (CHARS. length)]);} return buffer. toString ();}/*** returns an image with a number * @ return BufferedImage */public static BufferedImage getAuthImg (String authCode) {// set the image height, width, type, and RGB encoding: red, green, and blueBufferedImage img = new BufferedImage (IMG_WIDTH, IMG_HEIGHT, BufferedImage. TYPE_INT_BGR); // obtain a paint brush Graphics g = img on the image. getGraphics (); // you can specify the paint brush color for background color g. setColor (Color. RED); // fill a rectangle with a paint brush. The coordinates, width, and height of the upper left corner of the rectangle are g. fillRect (0, 0, IMG_WIDTH, IMG_HEIGHT); // set the paint brush color to black for writing g. setColor (Color. BLACK); // set the font: ,, without the format, font size g. setFont (new Font ("", Font. PLAIN, SINGLECODE_HEIGHT + 5); // output the number char c; for (int I = 0; I <authCode. toCharArray (). length; I ++) {// obtain the character c = authCode at the corresponding position. charAt (I); // draw a string: the content to be drawn, the starting position, and the height g. drawString (c + "", I * (SINGLECODE_WIDTH + SINGLECODE_GAP) + SINGLECODE_GAP/2, IMG_HEIGHT);} Random random = new Random (); // interferon for (int I = 0; I <15; I ++) {int x = random. nextInt (IMG_WIDTH); int y = random. nextInt (IMG_HEIGHT); int x2 = random. nextInt (IMG_WIDTH); int y2 = random. nextInt (IMG_HEIGHT); g. drawLine (x, y, x + x2, y + y2);} return img ;}}

Here, you can also change the background color, number of verification codes, and interferon intensity of the image. If you are interested, set it as needed.
3. Generate a dynamic verification code servlet

GetAuthCodeServlet. java

Package com. mucfc; import java. io. IOException; import javax. imageio. imageIO; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse;/*** get the servlet that generates the verification code image * @ author Lin bingwen Evankaka (blog: http://blog.csdn.net/evankaka) * @ since 2015.6.22 */public class getAuthCodeServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String authCode = AuthCode. getAuthCode (); request. getSession (). setAttribute ("authCode", authCode); // Save the verification code to the session for later verification. write (AuthCode. getAuthImg (authCode), "JPEG", response. getOutputStream ();} catch (IOException e) {e. printStackTrace () ;}} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );}}
4. Call index and make correct input judgment

<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> In this case, it is determined in a jsp

5. web. xml settings

<?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>getAuthCodeServlet</servlet-name><servlet-class>com.mucfc.getAuthCodeServlet</servlet-class></servlet><servlet-mapping><servlet-name>getAuthCodeServlet</servlet-name><url-pattern>/servlet/GetAuthCodeServlet</url-pattern></servlet-mapping><welcome-file-list><welcome-file>index.html</welcome-file><welcome-file>index.htm</welcome-file><welcome-file>index.jsp</welcome-file><welcome-file>default.html</welcome-file><welcome-file>default.htm</welcome-file><welcome-file>default.jsp</welcome-file></welcome-file-list></web-app>

6. Running Effect


Iii. Implementation of Dynamic verification codes similar to CSDN

The entire project structure remains unchanged

1. Change AuthCode to the following:

Package com. mucfc; import java. awt. color; import java. awt. graphics; import java. awt. font; import java. awt. image. bufferedImage; import java. util. arrayList; import java. util. list; import java. util. random;/*** generate Verification Code image * @ author Lin bingwen Evankaka (blog: http://blog.csdn.net/evankaka) * @ since 2015.6.22 */public class AuthCode {public static final int AUTHCODE_LENGTH = 5; // The verification code length is public static final int SINGLECODE_WIDTH = 20; // The width of a single verification code is public static final int SINGLECODE_HEIGHT = 30; // the height of a single verification code is public static final int SINGLECODE_GAP = 4; // The interval between a single verification code is public static final int IMG_WIDTH = AUTHCODE_LENGTH * (SINGLECODE_WIDTH + SINGLECODE_GAP); public static final int IMG_HEIGHT = SINGLECODE_HEIGHT; public static final char [] CHARS = {'0', '1', '2', '3', '4', '5', '6 ', '7', '8', '9'}; public static final char [] OPERATION = {'+ ','-','*'}; static Random random = new Random ();/*** return the number * @ return String */public static List <String> getAuthCode () {char char1 = CHARS [random. nextInt (CHARS. length)]; char char2 = CHARS [random. nextInt (CHARS. length)]; char opt = OPERATION [random. nextInt (OPERATION. length)]; StringBuffer buffer = new StringBuffer (); buffer. append (char1); buffer. append (getOperation (opt); buffer. append (char2); String result = getResult (char1, char2, opt); List <String> list = new ArrayList <String> (); list. add (buffer. toString (); list. add (result); return list;}/*** return calculation result * @ param operation * @ return String */public static String getResult (char char1, char char2, char operation) {int int1 = Integer. parseInt (String. valueOf (char1); int int2 = Integer. parseInt (String. valueOf (char2); if ('+' = operation) return String. valueOf (int1 + int2); else if ('-' = operation) return String. valueOf (int1-int2); else if ('*' = operation) return String. valueOf (int1 * int2); elsereturn null;}/*** returns the Chinese character corresponding to the symbol * @ param operation * @ return String */public static String getOperation (char operation) {if ('+' = operation) return "plus"; else if ('-' = operation) return "minus"; else if ('*' = operation) return "multiplied by"; elsereturn null;}/*** returns an image with a number * @ return BufferedImage */public static BufferedImage getAuthImg (String authCode) {// set the image height, width, type, and RGB encoding: red, green, and blueBufferedImage img = new BufferedImage (IMG_WIDTH, IMG_HEIGHT, BufferedImage. TYPE_INT_BGR); // obtain a paint brush Graphics g = img on the image. getGraphics (); // you can specify the paint brush color for background color g. setColor (Color. YELLOW); // use a paint brush to fill a rectangle. The coordinates, width, and height of the upper left corner of the rectangle are g. fillRect (0, 0, IMG_WIDTH, IMG_HEIGHT); // set the paint brush color to black for writing g. setColor (Color. BLACK); // set the font: ,, without the format, font size g. setFont (new Font ("", Font. PLAIN, SINGLECODE_HEIGHT + 5); // output the number char c; for (int I = 0; I <authCode. toCharArray (). length; I ++) {// obtain the character c = authCode at the corresponding position. charAt (I); // draw a string: the content to be drawn, the starting position, and the height g. drawString (c + "", I * (SINGLECODE_WIDTH + SINGLECODE_GAP) + SINGLECODE_GAP/2, IMG_HEIGHT);} Random random = new Random (); // interferon for (int I = 0; I <5; I ++) {int x = random. nextInt (IMG_WIDTH); int y = random. nextInt (IMG_HEIGHT); int x2 = random. nextInt (IMG_WIDTH); int y2 = random. nextInt (IMG_HEIGHT); g. drawLine (x, y, x + x2, y + y2);} return img ;}}
2. Change getAuthCodeServlet to the following:

Package com. mucfc; import java. io. IOException; import java. util. list; import javax. imageio. imageIO; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse;/*** get the servlet that generates the verification code image * @ author Lin bingwen Evankaka (blog: http://blog.csdn.net/evankaka) * @ since 2015.6.22 */public class getAuthCodeServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {List <String> list = AuthCode. getAuthCode (); request. getSession (). setAttribute ("authCode", list. get (1); // Save the verification code to the session for later verification try {// send image ImageIO. write (AuthCode. getAuthImg (list. get (0), "JPEG", response. getOutputStream ();} catch (IOException e) {e. printStackTrace () ;}} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );}}
Nothing else changes

Effect after running:


Original works of Lin bingwen Evankaka. Reprinted please indicate the source http://blog.csdn.net/evankaka

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.