Java Web: Generating a Web page random image verification code using a servlet

Source: Internet
Author: User
Tags set background

Recently in the study of Java Web development, made a page to generate a random image verification code example, in this record.

First, the new Servlet project:

New Servlet project in MyEclipse, step by step operation is OK, here no longer repeat. After building the file directory tree such as:

Second, the source code implementation:

(1) Java code:

Package Com.zdt.identity;import Java.awt.color;import Java.awt.font;import java.awt.graphics2d;import Java.awt.image.bufferedimage;import Java.io.ioexception;import Java.io.printwriter;import Java.util.Random;import Javax.servlet.servletexception;import Javax.servlet.servletoutputstream;import Javax.servlet.http.HttpServlet; Import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Com.sun.image.codec.jpeg.jpegcodec;import Com.sun.image.codec.jpeg.jpegimageencoder;public class Servlet1 extends HttpServlet {//random character Set 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 '};//random number public static random Random = new random ();//Get 6-bit random number public static string getrandomstring () {//string cache StringBuffer Strbuffer = new StringBuffer () ;//Loop out the character set randomly 6 characters for (int i = 0; i < 6; i++) {Strbuffer.append (Chars[random.nextint (chars.length)]);} return sTrbuffer.tostring ();} Gets the random color public static color Getrandomcolor () {return new color (Random.nextint (255), Random.nextint (255), Random.nextint (255));} Gets the inverse color of a color public static color Getreversecolor (color c) {return new color (255-c.getred (), 255-c.getgreen (), 255-c.ge Tblue ());} /** * Constructor of the object. */public Servlet1 () {super ();} /** * Destruction of the servlet. <br> */public void Destroy () {Super.destroy ();//Just puts "destroy" string in log//Put your code here}/** * the D Oget method of the servlet. <br> * This method was called when a form have its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the Client * @throws servletexception If an error occurred * @throws IOException If an error occurred */public void Doget (Http ServletRequest request, HttpServletResponse response) throws Servletexception, IOException {//Set the type of output, Here is the picture Response.setcontenttype ("Image/jpeg");//Gets the random string randomstring = Getrandomstring ();//binds the random string to the current session request.getsession (TRUE). SetAttribute (" RandomString ", randomstring); int width = 100;//picture width int height = 30;//picture height//Gets a random color colored color = Getrandomcolor ();// Gets the inverse color color of the above color Reversecolor = Getreversecolor (color);//Creates a color picture bufferedimage bi = new BufferedImage (width, depending on width and height) Height, BUFFEREDIMAGE.TYPE_INT_BGR);//Get drawing object graphics2d graphics2d = Bi.creategraphics ();//Set Font Graphics2d.setfont ( New Font (Font.sans_serif, Font.Bold, 16));//Set color graphics2d.setcolor (color);//Draw background graphics2d.fillrect (0, 0, width, height);//Set background color, opposite to character Color Graphics2d.setcolor (reversecolor);//Draw random character graphics2d.drawstring (RandomString, 18, 20);// Draw a random noise point, draw up to 100 for (int i = 0, n = random.nextint), i < n; i++) {Graphics2d.drawrect (Random.nextint (width), random . Nextint (height), 1, 1);} Output stream of the response servletoutputstream Servletoutputstream = Response.getoutputstream ();//convert to JPEG format JPEGImageEncoder encoder = Jpegcodec.createjpegencoder (Servletoutputstream);//encode the image encodeR.encode (BI);//output to client Servletoutputstream.flush ();} /** * The DoPost method of the servlet. <br> * This method was called when a form have its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the Client * @throws servletexception If an error occurred * @throws IOException If an error occurred */public void DoPost (HTT Pservletrequest request, HttpServletResponse response) throws Servletexception, IOException {}/** * initialization of the Servlet. <br> * * @throws servletexception If an error occurs */public void init () throws Servletexception {//Put your code Here}}
Note: You may get an error when importing JPEG picture processing packages Jpegcodec and JPEGImageEncoder, solution see: http://blog.csdn.net/u013149325/article/details/44838283

(2) write the Web. XML configuration file, the main code is as follows:

<servlet><servlet-name>servlet1</servlet-name><display-name>this is the display name of my Java Component</display-name><description>this is the description of my EE component</description> <servlet-class>com.zdt.identity.Servlet1</servlet-class></servlet><servlet-mapping> <servlet-name>servlet1</servlet-name><url-pattern>/servlet/servlet1</url-pattern></ Servlet-mapping>

(3) write the HTML file with the following code:

<! DOCTYPE html>
III. Deployment of Procedures

tutorial on installing Tomcat and deploying it as a Windows service: http://www.blogjava.net/lushengdi/archive/2010/07/01/324952.html

Locate the Tomcat installation directory, create a new folder under the WebApps directory, name servlettest, copy all the files under the project's compiled Webroot folder to the Servlettest folder, and Tomcat will automatically load the project.

Iv. Presentation of results

in the browser address bar, enter: http://localhost:8080/servletTest/identity.html, enter, results such as:


Click "Change Picture" button, the picture will change


Java Web: Generating a Web page random image verification code using a servlet

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.