Using Java to implement login verification code (full code)

Source: Internet
Author: User
Tags gettext int size time limit

First, write a verification code tool class

Package Com.yx.cus.util;import Java.awt.basicstroke;import Java.awt.color;import java.awt.font;import Java.awt.graphics2d;import Java.awt.image.bufferedimage;import Java.io.ioexception;import Java.io.OutputStream;    Import Java.util.random;import Javax.imageio.imageio;public class Verifycode {private int w = 70;    private int h = 35;    Private random R = new Random ();  {"Arial", "Chinese Italic", "Black Body", "Chinese New Wei", "Chinese Script", "Microsoft Jas Black", "italics _gb2312"} private string[] FontNames = {"Arial", "Chinese Italic", "Black Body", "Microsoft Ya-hei",    "Italics _gb2312"};    Private String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";    Private color BgColor = new color (255, 255, 255);    public static String text;        Private Color Randomcolor () {int red = R.nextint (150);        int green = R.nextint (150);        int blue = R.nextint (150);    return new Color (red, green, blue);        } private Font Randomfont () {int index = R.nextint (fontnames.length);        String fontname = Fontnames[index]; INT style = R.nextint (4);         int size = R.nextint (5) + 24;    return new Font (FONTNAME, style, size);//Specify the font name, style, and point size to create a new font. }//Draw interfering lines private void DrawLine (bufferedimage image) {int num = 3;//Draw three graphics2d g2 = (Graphics2        D) Image.getgraphics ();            for (int i = 0; i < num; i++) {int x1 = r.nextint (w);            int y1 = R.nextint (h);            int x2 = r.nextint (w);             int y2 = r.nextint (h);             G2.setstroke (New Basicstroke (1.5F));             G2.setcolor (Color.Blue);        G2.drawline (x1, y1, x2, y2);        }} private char Randomchar () {int index = R.nextint (Codes.length ());    Return Codes.charat (index); } private BufferedImage CreateImage () {bufferedimage image = new BufferedImage (W, H, Bufferedimage.type_int_rg         B);         graphics2d g2 = (graphics2d) image.getgraphics ();        G2.setcolor (This.bgcolor);        G2.fillrect (0, 0, W, h);    return image; } PUBlic bufferedimage getImage () {BufferedImage image = CreateImage ();        graphics2d g2 = (graphics2d) image.getgraphics ();        StringBuilder sb = new StringBuilder ();             Draw 4 characters to the picture for (int i = 0; i < 4; i++) {String s = Randomchar () + "";             Sb.append (s);             float x = i * 1.0F * W/4;             G2.setfont (Randomfont ());             G2.setcolor (Randomcolor ()); /** * The baseline of the first character is located at the (x, h-5) position of the user space * The origin is in the upper-left corner and the x-axis increments from left to right; The y-axis is from top to bottom * when the provided coordinates are on the leftmost character of the baseline, the glyph can be rendered right-to-left * h-5 represents the y-axis direction and is offset upward by 5 */G2.drawstri         Ng (S, x, h-5);         } This.text = Sb.tostring ();         DrawLine (image);           return image;    } public String GetText () {return text; public static void output (BufferedImage image, OutputStream out) throws IOException {ImageIO    . Write (Image, "JPEG", out); }}

This tool class we mainly use two methods:
1. Use the GetImage () method to make the verification code, return the BufferedImage type of verification code
2. Get the text of the captcha via the GetText () method, return the string type
Two. Interface for Verification Code (Controller)

/** * Verification Code * @param request * @return * @throws Exception * *  @RequestMapping (value = "/VC", method = Requestmethod.post) @ResponseBodypublic void  VC (httpservletrequest request, httpservletresponse response) throws exception{    Verifycode code=new Verifycode ();   BufferedImage image = Code.getimage ();   Save the Captcha text to Redis   Vckey=idutil.nextid ();   Jedisclient.set (Vckey, Code.gettext ();   Imageio.write (image, "JPG", Response.getoutputstream ()); }

The interface returns a verification code on the front end, returned as a stream, and a unique identifier is generated before the return is assigned to a global variable that is used to deposit the code in the Redis text for later use, and the text to be deposited has a time limit
Third, get the code text identification of the interface (that is, the value of the Verification Code text deposit)

/** * Identification of the CAPTCHA text * @param request * @return * @throws Exception * *   @RequestMapping (value = "/vckey", method = Reques Tmethod.post) @ResponseBodypublic String  Vckey (httpservletrequest request, httpservletresponse response) throws exception{        System.out.println (vckey);   return Vckey;}

The main interface is to put the key in the Redis code text back to the front end, and then log back to the login interface together
Four, login interface (sample)

String user_phone = Reqstr.get ("User_phone");//account string User_pwd   = Reqstr.get ("user_pwd");//password string VC   = Reqstr.get ("VC"). toLowerCase ();//The user enters a verification code string Vckey   = Reqstr.get ("Vckey");//The Key (identity) of the captcha text acquired by the front end string vcode= ( String) Jedisclient.get (Vckey);//Obtain CAPTCHA text if (Vc.equals (Vcode.tolowercase ())) {//user-entered verification code compared to redsi saved by identity   "Authenticode succeeded"}else if (vcode==null) {    "Authenticode expired"}else{     "Captcha Error"}

Add: The key (identity) of the verification code can also be generated on the front end, such as generating a timestamp, in the interface of the request verification code as a parameter, so that the background can write less one interface and global variables

Related articles:

Java Login Verification Code implementation codes

Implementation of JavaScript Login verification code

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.