SpringMVC Verification Code
SpringMVC
Preface:
1. the verification code is not recommended when you log on to the system at the beginning. This is already evident on many websites. You are required to enter the verification code only when the user fails three or more times in a row.
2. it is recommended that you do not use the session to record the number of user errors because the session is related to the client browser session. If you restart the browser or use a new browser to log on or try again, it is a new response, and the number of errors recorded in the past becomes invalid. it is recommended that the cache mechanism be used here. Simple processing is implemented by using Map <User Login id, number of errors>. If there are multiple server loads, another cache mechanism is required, for example, Redis is used.
3. After Entering the user name, you need to use the login name to determine whether verification code is required.
4. The generated verification code is bound to the session. Whether the verification code needs to be verified depends on the number of failures in the specified time.
The native servlet can write images directly to the client. However, the spring MVC shoes may not know how to return images under this framework. In fact, in essence, spring is the same as servlet. HttpServletResponse is used to return the image.
How to obtain the verification code in springMVC controller
/*** Generate the Verification Code * @ param request * @ param response */@ RequestMapping (value = "login/getVerifyCode") public void getVerifyCode (HttpServletRequest request, HttpServletResponse response) {response. setHeader ("Pragma", "No-cache"); response. setHeader ("Cache-Control", "no-cache"); response. setDateHeader ("Expires", 0); response. setContentType ("image/jpeg"); // generate a random String: String verifyCode = VerifyCodeUtils. generateVerifyCode (4); // save it to the Session. HttpSession session = request can be set as needed. getSession (); session. setAttribute ("verifyCode", verifyCode); // generate an image int w = 100, h = 35; try {// write the image to the response output stream to return the image to the client VerifyCodeUtils. outputImage (w, h, response. getOutputStream (), verifyCode);} catch (IOException e) {logger. error ("failed to generate verification code, Cause by: {}", e. getMessage (), e );}}
Class for generating Verification Code Images
One found on the Internet is not bad.
Import javax. imageio. imageIO; import java. awt. *; import java. awt. geom. affineTransform; import java. awt. image. bufferedImage; import java. io. file; import java. io. fileOutputStream; import java. io. IOException; import java. io. outputStream; import java. util. arrays; import java. util. random;/*** generate an image stream * @ Description: Created by zcqshine on. */public class VerifyCodeUtils {private static final String VER IFY_CODES = "23456789 ABCDEFGHJKLMNPQRSTUVWXYZ"; private static Random random = new Random (); /*** use the system default character source to generate a Verification Code * @ param verifySize verification code length * @ return */public static String generateVerifyCode (int verifySize) {return generateVerifyCode (verifySize, VERIFY_CODES );} /*** use the specified source to generate a Verification Code * @ param verifySize verification code length * @ param sources Verification Code character source * @ return */public static String generateVerifyCode (int verifySize, String sources) {if (sources = null | sources. trim (). length () = 0) {sources = VERIFY_CODES;} int codesLen = sources. length (); Random rand = new Random (System. currentTimeMillis (); StringBuilder verifyCode = new StringBuilder (verifySize); for (int I = 0; I <verifySize; I ++) {verifyCode. append (sources. charAt (rand. nextInt (codesLen-1);} return verifyCode. toString ();}/*** outputs the Random verification code image stream and returns the verification code. Verification code value * @ param w * @ param h * @ param outputFile * @ param verifySize * @ return */public static String outputVerifyImage (int w, int h, File outputFile, int verifySize) throws IOException {String verifyCode = generateVerifyCode (verifySize); outputImage (w, h, outputFile, verifyCode); return verifyCode ;} /*** generate the specified Verification Code image file * @ param w * @ param h * @ param outputFile * @ param verifyCode * @ throws IOException */Public static void outputImage (int w, int h, File outputFile, String verifyCode) throws IOException {if (outputFile = null) {return;} File dir = outputFile. getParentFile (); if (! Dir. exists () {dir. mkdirs ();} try {outputFile. createNewFile (); FileOutputStream fos = new FileOutputStream (outputFile); outputImage (w, h, fos, verifyCode); fos. close () ;} catch (IOException e) {throw e ;}} public static void outputImage (int w, int h, OutputStream OS, String code) throws IOException {int verifySize = code. length (); BufferedImage image = new BufferedImage (w, h, BufferedImage. TYPE _ INT_RGB); Random rand = new Random (); Graphics2D g2 = image. createGraphics (); g2.setRenderingHint (RenderingHints. KEY_ANTIALIASING, RenderingHints. VALUE_ANTIALIAS_ON); Color [] colors = new Color [5]; Color [] colorSpaces = new Color [] {Color. WHITE, Color. CYAN, Color. GRAY, Color. LIGHT_GRAY, Color. MAGENTA, Color. ORANGE, Color. PINK, Color. YELLOW}; float [] fractions = new float [colors. length]; for (int I = 0; I <colors. length; I ++) {colors [I] = colorSpaces [rand. nextInt (colorSpaces. length)]; fractions [I] = rand. nextFloat ();} Arrays. sort (fractions); g2.setColor (Color. GRAY); // set the border Color g2.fillRect (200,250, w, h); Color c = getRandColor (); g2.setColor (c); // set the background Color g2.fillRect (0, 2, w, H-4); // draw interference line Random random = new Random (); g2.setColor (getRandColor (160,200); // set the line color for (int I = 0; I <20; I + +) {Int x = random. nextInt (w-1); int y = random. nextInt (h-1); int xl = random. nextInt (6) + 1; int yl = random. nextInt (12) + 1; g2.drawLine (x, y, x + xl + 40, y + yl + 20);} // Add the noise float yawpRate = 0.05f; // noise rate int area = (int) (yawpRate * w * h); for (int I = 0; I <area; I ++) {int x = random. nextInt (w); int y = random. nextInt (h); int rgb = getRandomIntColor (); image. setRGB (x, y, rgb);} s Hear (g2, w, h, c); // twist the image g2.setColor (getRandColor (100,160); int fontSize = H-4; Font font = new Font ("Algerian ", font. ITALIC, fontSize); g2.setFont (font); char [] chars = code. toCharArray (); for (int I = 0; I <verifySize; I ++) {AffineTransform affine = new AffineTransform (); affine. setToRotation (Math. PI/4 * rand. nextDouble () * (rand. nextBoolean ()? 1:-1), (w/verifySize) * I + fontSize/2, h/2); g2.setTransform (affine); g2.drawChars (chars, I, 1, (w-10) /verifySize) * I + 5, h/2 + fontSize/2-10);} g2.dispose (); ImageIO. write (image, "jpg", OS);} private static Color getRandColor (int fc, int bc) {if (fc> 255) fc = 255; if (bc> 255) bc = 255; 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);} private static int getRandomIntColor () {int [] rgb = getRandomRgb (); int color = 0; for (int c: rgb) {color = color <8; color = color | c;} return color;} private static int [] getRandomRgb () {int [] rgb = new int [3]; for (int I = 0; I <3; I ++) {rgb [I] = random. nextInt (255);} return rgb;} private static void shear (Graphics g, int w1, int h1, Color color) {shearX (g, w1, h1, color ); shearY (g, w1, h1, color);} private static void shearX (Graphics g, int w1, int h1, Color color) {int period = random. nextInt (2); boolean borderGap = true; int frames = 1; int phase = random. nextInt (2); for (int I = 0; I
Thank you for reading this article. I hope it will help you. Thank you for your support for this site! If you have any questions, please leave a message or go to the community on this site to discuss and make common progress!