The generation of servlet imitation csdn dynamic Verification code-with numbers and letters

Source: Internet
Author: User

Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka

First, the realization of the idea:

(1) First, you need to create a servlet. The servlet returns a picture to the client through a byte-type response. The picture is generated from the Java 2D Class library in the JDK.

The image is generated by a random number and then the random number is written in the image format. At the end of the session, the State of the random string is persisted so that the user can complete the comparison.
(2) second, in the JSP page that needs to join the verification code, the picture is introduced by .

(3) finally. Once a single user has completed the verification code. Commit to a servlet. In this servlet, the user-joined verification code is obtained through the Request.getparameter () method. Then after the check out and the session generated by the verification code to control, assuming that the success of the pass, otherwise return the page to the user prompted the wrong captcha information.

(4) Then assume that to imitate CSDN dynamic verification code, it is necessary to generate numbers and symbols (+. -。 *)。 According to the symbol, calculate the result, calculate the Chinese, and store the result in a list<string>.


First look at the effect:



Second, the Code

The first implementation here is only numbers and letters. With no symbolic operation

Item download

1. Project overall structure


2. Generate code with numbers and pictures

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 captcha 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;//CAPTCHA length public static f inal int singlecode_width = 15; Single Captcha width public static final int singlecode_height = 30; Individual captcha height public static final int singlecode_gap = 4; Interval between individual captcha public static final int img_width = Authcode_length * (singlecode_width + singlecode_gap);p ublic 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 (); /** * Returns the number in the picture * @return string */public static string Getauthcode () {StringBuffer buffer = new StringBuffer () ; for (int i = 0; i < 5; i++) {//Generate 6 characters buffer.append (Chars[random.nextint (chars.length)]);} return buffer.tostring ();} /** * Returns a picture with a number * @return bufferedimage */public static bufferedimage getauthimg (String authcode) {//Set picture height, width, Type//RGB encoding: Red, green, bluebufferedimage img = new BufferedImage (img_width, IMG_HEIGHT,BUFFEREDIMAGE.TYPE_INT_BGR);// Get a paintbrush on the picture on the graphics g = img.getgraphics ();//Set the color of the brush to make the background color g.setcolor (color.red);//Fill a rectangle with a brush, the upper-left corner of the rectangle, the coordinates, width. High G.fillrect (0, 0, img_width, img_height);//The brush color is set to black, used to write G.setcolor (color.black);//Set font: Arial, unformatted, Font size g.setfont (new Font ("Arial", Font.plain, Singlecode_height + 5));//output digit char c;for (int i = 0; i < Authcode.tochararray (). length; i++) {/ /take to the corresponding position of the character C = Authcode.charat (i);//Draw a string: the content to be drawn, the starting position, the height of g.drawstring (c + "", I * (Singlecode_width + singlecode_gap) + S INGLECODE_GAP/2, img_height);} Random Random = new Random ();//interferon for (int i = 0; i < i++) {int x = Random.nextint (img_width); int y = Random.nextint (img_heigh T); int x2 = Random.nextint (img_width); int y2 = Random.nextint (img_height); G.drawline (x, y, x + x2, y + y2);} return img;}}

Here can also change the background color of the picture, the number of verification code, interferon intensity, etc., interested students to set up their own well
3. servlet that generates dynamic verification code

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 a servlet that generates a CAPTCHA image * @author Lin Bingwen evankaka (blog: http://blog.csdn.net/ Evankaka) * @since 2015.6.22 */public class Getauthcodeservlet extends HttpServlet {public void doget (HttpServletRequest r                   Equest, HttpServletResponse response) throws Servletexception, IOException {String authcode = Authcode.getauthcode ();    Request.getsession (). SetAttribute ("Authcode", Authcode); Save the Verification code to the session. Easy to verify later try {//Send picture Imageio.write (authcode.getauthimg (Authcode), "JPEG", resp          Onse.getoutputstream ());          } catch (IOException e) {e.printstacktrace (); }}public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Doget (Request,response);}} 
4, Index call, and enter the correct inference

<%@ 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" >

Please enter again! "); }}%><br> <input type= "Submit" value= "Submission" > </form> </body>

this is inferred directly 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/XMLS Chema-instance "xsi:schemalocation=" Http://java.sun.com/xml/ns/javaee Http://java.sun.com/xml/ns/javaee/web-ap P_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. Execution Effect


Implementation of dynamic verification code for imitation CSDN

The entire project structure is unchanged.

Item two download

1, Authcode change to such as 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 picture * @author Lin Bingwen evankaka (blog: http://blog.csdn.net/evankaka) * @since 2015.6.22 */public class Authcode {public static final in T authcode_length = 5; Captcha length public static final int singlecode_width = 20; Single Captcha width public static final int singlecode_height = 30; Individual captcha height public static final int singlecode_gap = 4; Interval between individual captcha public static final int img_width = Authcode_length * (singlecode_width + singlecode_gap);p ublic static final int img_height = singlecode_height;public static final char[] CHARS = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 '};p    Ublic static final char[] operation={' + ', '-', ' * '};static random random = new random (); /** * Returns the number in the picture * @return String */public static list<string> Getauthcode () {Char char1 = chars[random.ne Xtint (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;} /** * Returns the result of the calculation * @param operation * @return string */public static string GetResult (char Char1,char char2,c Har 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;} /** * return symbol corresponding to Chinese * @param operation * @return string */public static string getoperation (char operation) {if (' + ' ==operation) return ' plus ', else if ('-' ==operation ') return ' minus ';else if (' * ' ==operation) return "multiplied"; Elsereturn null;} /** * Returns a picture with a number * @return bufferedimage */public static bufferedimage getauthimg (String authcode) {//Set picture height, width, Type//RGB encoding: Red, green, bluebufferedimage img = new BufferedImage (img_width, IMG_HEIGHT,BUFFEREDIMAGE.TYPE_INT_BGR);// Get a paintbrush on the picture of the graphics G = img.getgraphics ();//Set the color of the brush to make the background color g.setcolor (color.yellow);//Fill a rectangle with a brush. The upper-left corner coordinates of the rectangle, width, height g.fillrect (0, 0, img_width, img_height);//Set the brush color to black, used to write G.setcolor (color.black);//Set font: Arial, unformatted, Font size g.setfont (new font ("Arial", Font.plain, Singlecode_height + 5));//output digit char c;for (int i = 0; i < Authcode.tochararray () . length; i++) {//the character C = Authcode.charat (i) is taken to the corresponding position;//Draw a string: the content to be drawn. Start position, 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.nextin T (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, Getauthcodeservlet change to such as 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 generated the CAPTCHA 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 CAPTCHA to the session for later verification of the try {//Send picture Imageio.write (list. authcode.getauthimg).          Get (0)), "JPEG", Response.getoutputstream ());          } catch (IOException e) {e.printstacktrace (); }}public void DoPost (HttpServletRequest request, httpservletresponse response) throws SeRvletexception, IOException {doget (request,response);}} 
Everything else doesn't change .

Post-execution effects:


Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka

The generation of servlet imitation csdn dynamic Verification code-with numbers and letters

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.