JSP practical tutorial-Implementation of simple image Verification Code (with source code), jsp practical tutorial

Source: Internet
Author: User

JSP practical tutorial-Implementation of simple image Verification Code (with source code), jsp practical tutorial

Preface

Many new users do not know the image verification code very well. Therefore, this article attempts to use a simple JSP applet to implement the verification code function. The detailed sample code is provided in this article, and the complete instance code is provided at the end of this article. I will not talk much about it below. Let's take a look at the detailed introduction.

Sample Code

The front-end code is as follows:

<Form action = "action. jsp "method =" POST "> <label> User Name: <input type = "text" name = "name" data-singleTips = "Enter the username" value = "admin"/> </label> <label> password: <input type = "password" name = "password"/> </label> <! -- Verification code --> <label class = "captchaCode"> Verification Code:  <input type =" text "name =" captchaImgCode "/> </label> <div> <input type =" submit "value =" Logon "/> </ div> </form>

Where does the verification code image come from? Img. jsp is also:

<% @ Include file = "captcha. jsp" %> <% init (pageContext); // load image %>

Returns the data stream of the image.

Action. jsp does not check the user name or password, but only the verification code.

If the verification code is passed, it is displayed as follows:

Conversely, the following exceptions are caught:

Action. jsp is called in captcha. jspisPass(pageContext, captchaImgCode)Method, and capture known exceptions.

<% @ Page pageEncoding = "UTF-8" %> <% @ include file = "captcha. jsp "%> <% String captchaImgCode = request. getParameter ("captchaImgCode"); try {if (isPass (pageContext, captchaImgCode) {out. println ("Verification Code passed! ") ;}} Catch (Throwable e) {out. println (e) ;}%>

Core captcha and jsp code:

<% @ Page pageEncoding = "UTF-8" import = "java. io. IOException, java. awt. *, java. awt. image. bufferedImage, java. util. random, javax. imageio. imageIO "%> <%! // Define the Captcha class public static class Captcha {/*** default width 60 */private int width = 60;/*** default height 20 */private int height = 20; /*** Verification code */private String code;/*** generate Verification code image *** @ return image object */public BufferedImage get () {BufferedImage image = new BufferedImage (width, height, BufferedImage. TYPE_INT_RGB); // create the image Graphics g in the memory; g = image. getGraphics (); // obtain the graph context g. setColor (getRandColor (200,250) ); // Set the background g. fillRect (0, 0, width, height); g. setFont (new Font ("Times New Roman", Font. PLAIN, 18); // set the font g. setColor (getRandColor (160,200); Random random = new Random (); // Random interference line for (int I = 0; I <155; I ++) {int x = random. nextInt (width), y = random. nextInt (height); int xl = random. nextInt (12), yl = random. nextInt (12); g. drawLine (x, y, x + xl, y + yl);} String sRand = ""; // a four-digit Verification Code fo is randomly generated. R (int I = 0; I <4; I ++) {String rand = String. valueOf (random. nextInt (10); sRand + = rand; g. setColor (new Color (20 + random. nextInt (110), 20 + random. nextInt (110), 20 + random. nextInt (110); // display the ID code in the image g. drawString (rand, 13 * I + 6, 16); // The color from the called function is the same, probably because the seed is too close, so you can only directly generate} // Save the authentication code to the SESSION // session. setAttribute ("rand", sRand); setCode (sRand); g. dispose (); // return image for effective image;}/*** generate random face Filter Color ** @ param fc * @ param bc * @ return */private Color getRandColor (int fc, int bc) {if (fc> 255) fc = 255; if (bc> 255) bc = 255; Random random = new Random (); int r = fc + random. nextInt (bc-fc); int g = fc + random. nextInt (bc-fc); int B = fc + random. nextInt (bc-fc); return new Color (r, g, B);}/*** get height ** @ return */public int getHeight () {return height;}/*** set height ** @ param hei Ght * height */public void setHeight (int height) {this. height = height;}/*** obtain the verification code ** @ return */public String getCode () {return code ;} /***** set the verification code ** @ param code * Verification code */public void setCode (String code) {this. code = code;}/*** get width ** @ return */public int getWidth () {return width ;} /***** set the width ** @ param width */public void setWidth (int width) {this. width = width ;}}/*** SE SSION key value */public static final String SESSION_KEY = "rand "; /*** display the verification code image and save the verification code to the Session ** @ param response * response object * @ param session * session object */public static void init (HttpServletResponse response, HttpSession Session) {Captcha img = new Captcha (); // response is not cached. setHeader ("Pragma", "No-cache"); response. setHeader ("Cache-Control", "no-cache"); response. setDateHeader ("Expires", 0); response. set ContentType ("image/jpg"); try {ImageIO. write (img. get (), "JPEG", response. getOutputStream ();/** with the following code, java will not appear at runtime. lang. illegalStateException: getOutputStream () has already been called .......... * response. getOutputStream (). flush (); * response. getOutputStream (). close (); * response. flushBuffer (); * // JSP built-in objects out and response. the main difference between getWrite () and getWrite () is as follows: 1. the types of these two objects are completely different ...... // Response. getWriter ();// http://blog.sina.com.cn/s/blog_7217e4320101l8gq.html // http://www.bkjia.com/kf/201109/103284.html // PageContext. getOut (). clear ();} catch (IOException e) {e. printStackTrace ();} session. setAttribute (SESSION_KEY, img. getCode (); // Save the authentication code to the SESSION System. out. println ("generate Verification Code:" + img. getCode ();}/*** display the verification code image and save the verification code to the Session (For JSP) ** @ param pageContext * Page Context object */public static void init (PageContext pageContext) {init (HttpServletResponse) pageContext. getResponse (), pageContext. getSession () );} /*** Determines whether the user-entered verification code is passed through the ** @ param pageContext * Page Context object * @ return true, which indicates the use of * @ throws Throwable */public static boolean isPass (PageContext pageContext, string code) throws Throwable {boolean isCaptchaPass = false; String rand = (String) pageContext. getSession (). getAttribute (SESSION_KEY); System. out. println ("rand:" + rand); System. out. println ("CaptchaCode:" + code); if (rand = null) throw new UnsupportedOperationException ("Please refresh the verification code. "); Else if (code = null | code. equals ("") {throw new IllegalArgumentException ("Verification Code Parameter not provided");} else {isCaptchaPass = rand. equals (code); if (! IsCaptchaPass) throw new IllegalAccessError ("Incorrect verification code");} return isCaptchaPass; }%>

Download complete code:Http://xiazai.jb51.net/201707/yuanma/Captcha (jb51.net).rar

Summary

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

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.