Generation of servlet dynamic verification codes-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 that generates a picture 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 kept in order to be compared after the user fills it out.
(2) second, in the JSP page that needs to join the verification code, the picture is introduced by .

(3) Finally, a single user completes the verification code and submits it to a servlet. In this servlet, the user-added verification code is obtained through the Request.getparameter () method, then compared with the verification code generated in the session, if the success of the comparison is passed, otherwise the page is returned to the user to indicate the error of the CAPTCHA.

First look at the effect:



Second, the Code

1, the overall structure of the project


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 coordinates of the rectangle, the 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 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 you 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 for later verification try {//Send picture Imageio.write (authcode.getauthimg (authc          ODE), "JPEG", Response.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 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" >Here directly in a JSP to judge the
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. Operation Effect


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

Generation of servlet dynamic verification codes-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.