Java Web Verification Code

Source: Internet
Author: User

Java Web Verification Code
1. RandomCode

RandomCode is a tool class for generating verification codes. It supports both English and digital verification codes. The verification codes include uppercase and lowercase letters and arrays. English I, o, and numbers 0 and 1 are confusing, not included in the verification code generation. RandomCode supports outputting jpg, bmp, png, and GIF verification codes.

 

/*** The RandomCode verification code can be generated using static methods and instance methods. ** Static method: ** // generate a 4-digit random Verification code * String code = RandomCode. randomString (4); ** // input the verification code image to the response output stream * // jpg * OutputStream OS = response. getOutputStream (); * RandomCode. write (code, 120, 30, OS, jpg); ** instance method: ** // instantiate the verification code class * RandomCode rc = new RandomCode (4 ); ** // input the verification code image to the response output stream * // jpg * OutputStream OS = response. getOutputStream (); * rc. write (120, 30, OS, jpg); ** // obtain the verification code String * String code = rc. getCode (); **/public class RandomCode {/*** Random verification code character */private static String base = abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789; /***** Random verification code length */private int length = 4;/***** verification code String */private String code; /*** 4-digit random Verification Code */public RandomCode () {this. code = RandomCode. randomString (this. length);} public RandomCode (int length) {if (length> 0) {this. length = length;} this. code = RandomCode. randomString (this. length);}/*** generate Verification Code image * @ param width Image width * @ param height image height * @ return */public BufferedImage toImage (int width, int height) {return RandomCode. toImage (this. code, width, height);}/*** output verification code image, the default image format is jpeg * @ param width * @ param height * @ param OS * @ throws IOException */public void write (int width, int height, OutputStream OS) throws IOException {RandomCode. write (code, width, height, OS, jpeg);}/*** output verification code image * @ param width * @ param height * @ param OS * @ param format, supports jpg/jpeg/bmp/gif/png * @ throws IOException */public void write (int width, int height, OutputStream OS, String format) throws IOException {RandomCode. write (code, width, height, OS, format);} public int getLength () {return length;} public String getCode () {return code ;} /*** static method ** to generate a Random String * @ param length String length * @ return random String */public static String randomString (int length) {Random = new random (); stringBuffer sb = new StringBuffer (); for (int I = 0; I <length; I ++) {sb. append (base. charAt (random. nextInt (base. length ();} return sb. toString ();} /* ** Static Method * output verification code image * @ param code verification code string * @ param width Image width * @ param height image height * @ param OS image output stream * @ param format Image format, jpg/jpeg/bmp/gif/png * @ throws IOException */public static void write (String code, int width, int height, OutputStream OS, String format) throws IOException {BufferedImage image = toImage (code, width, height); ImageIO. write (image, format, OS);}/*** Static Method * outputs the verification code image, default image format jpeg * @ param code verification code string * @ param width Image width * @ param height image height * @ param OS image output stream * @ throws IOException */public static void write (string code, int width, int height, OutputStream OS) throws IOException {write (code, width, height, OS, jpeg );} /*** convert a static method * string to a verification code image * @ param code verification code string * @ param width: The image width of the verification code, in pixels * @ param height: The Image height of the verification code, unit pixel * @ return */public static BufferedImage toImage (String code, int width, int height) {// fontSize int fontSize = (int) Math. ceil (height * 0.9); if (fontSize <20) {fontSize = 20;} // The Position of the font on the Y coordinate int positionY = (int) Math. ceil (height * 0.8); int lenCode = code. length (); // calculate the font width int fontWidth = width/(lenCode + 2); BufferedImage image = new BufferedImage (width, height, BufferedImage. TYPE_INT_BGR); Graphics g = image. getGraphics (); // random color of the image background g. setColor (randomColor (new Random (), 200,250); g. fillRect (0, 0, width, height); // set the font g. setFont (new Font (Times New Roman, Font. BOLD, fontSize); // draw lines in the picture to achieve the obfuscation effect drawLines (g, width, height); // draw the verification code drawString (g, code, fontWidth, positionY); g. dispose (); return image ;} /*** static method ** on the image, talk to the seat * @ param g * @ param code verification code string * @ param fontWidth font width * @ param positionY font Y coordinate */private static void drawString (Graphics g, string code, int fontWidth, int positionY) {int len = code. length (); Random random = new Random (); for (int I = 0; I <len; I ++) {g. setColor (randomColor (random); g. drawString (String. valueOf (code. charAt (I), (I + 1) * fontWidth, positionY);} private static Color randomColor (Random random) {int r = random. nextInt (255); int g = random. nextInt (255); int B = random. nextInt (255); return new Color (r, g, B);} private static Color randomColor (Random random, int fc, int bc) {if (fc> 255) {fc = 255;} if (bc> 255) {bc = 255;} int diff = bc-fc; int r = fc + random. nextInt (diff); int g = fc + random. nextInt (diff); int B = fc + random. nextInt (diff); return new Color (r, g, B );} /** static Method * draw a line that is crossly And crossly crossed * @ param g * @ param width Verification Code Image width * @ param height Verification Code Image height */private static void drawLines (Graphics g, int width, int height) {Random random = new Random (); // number of rows int count = (int) (Math. ceil (random. nextDouble () * 100) + 100; for (int I = 0; I <count; I ++) {int fc = 160 + (int) Math. ceil (random. nextDouble () * 40); int bc = 200 + (int) Math. ceil (random. nextDouble () * 55); g. setColor (randomColor (random, fc, bc); int x = random. nextInt (width); int y = random. nextInt (height); int xl = random. nextInt (width/5); int yl = random. nextInt (height/5); g. drawLine (x, y, x + xl, y + yl );}}}

2 Servlet return verification code

Request Path http: // <website path>/random/code/servlet

 

@ WebServlet (/random/code/servlet) public class RandomCodeServlet extends HttpServlet {private static final long serialVersionUID = 1L; protected void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// Verification Code image width, in pixels int width = 120; // Verification Code Image height, in pixels int height = 30; // Verification Code image format String format = png; // The length of the verification code is int len = 4; // set the image format response. setContentType (image/+ format); // disable the browser from caching the image response. setHeader (Pragma, no-cache); response. setHeader (Cache-Control, no-cache); response. setDateHeader (Expires, 0); String code = RandomCode. randomString (len); // output the image to the response output stream RandomCode. write (code, width, height, response. getOutputStream (), format );}}

3 Strust2 return verification code

 

Public class RandomCodeAction extends ActionSupport {private static final long serialVersionUID =-7515645222798283236L;/*** get Verification Code */public void generateCode () {HttpServletResponse response = ServletActionContext. getResponse (); // The image width of the verification code, in the unit of int width = 120; // The Image height of the verification code, in the unit of int height = 30; // The image format of the verification code is String format = png; // The length of the verification code is int len = 4; // set the image format response. setContentType (image/+ format); // disable the browser from caching the image response. setHeader (Pragma, no-cache); response. setHeader (Cache-Control, no-cache); response. setDateHeader (Expires, 0); String code = RandomCode. randomString (len); // output the image to the response output stream try {RandomCode. write (code, width, height, response. getOutputStream (), format);} catch (IOException e) {e. printStackTrace ();}}}

Struts2 verification code configuration

 

 

Request Path http: // <website path>/randomCode_generateCode.do


4 SpringMVC return verification code

Request Path http: // <website path>/random/code/generate. do

 

Package com. rhui. web. controller; import java. io. IOException; import javax. servlet. http. httpServletResponse; import org. springframework. stereotype. controller; import org. springframework. web. bind. annotation. requestMapping; import com. rhui. util. randomCode; @ Controller @ RequestMapping (/random/code) public class RandomCodeController {@ RequestMapping (/generate. do) public void generateCode (HttpServletResponse response) {// The image width of the verification code, in the unit of int width = 120; // The Image height of the verification code, in the unit of int height = 30; // Verification Code image format String format = png; // The Verification Code character length int len = 4; // set the image format response. setContentType (image/+ format); // disable the browser from caching the image response. setHeader (Pragma, no-cache); response. setHeader (Cache-Control, no-cache); response. setDateHeader (Expires, 0); String code = RandomCode. randomString (len); // output the image to the response output stream try {RandomCode. write (code, width, height, response. getOutputStream (), format);} catch (IOException e) {e. printStackTrace ();}}}



 

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.