Written in front
Some time ago, we all said that the environment is not good recently. Many companies are laying off employees. If they change jobs, they don't recommend easy naked words. But what I want to say is that my company has abuses, there are business needs that can't be done, and there are people who can't be recruited. Recently, I have been busy, but I still need to take a little time to do self-rewriting and recording. Recently, I have also written a simple small function, that is, the image verification code function of the landing interface.
Environment: Tomcat 9, Jdk1.8
1 Tool Class for Generating Verification Codes
public class RandomValidateCodeUtil { public static final String RANDOMCODEKEY= "RANDOMVALIDATECODEKEY";//key in session private String randString = "0123456789";//Random Generation of a Number-Only String private String //Private String randString = ABCDEFGHIJKLMNOPQRSTUVWXYZ; //Random generation of alphabetic strings //Private String randString = 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ; //Random Generation of Number and Letter Combination Strings private int width = 95;// Picture width private int height = 25;// Picture height private int lineSize = 40;// Number of interference lines private int stringNum = 4;// Number of randomly generated characters private static final Logger logger = LoggerFactory.getLogger(RandomValidateCodeUtil.class); private Random random = new Random(); /** * Get font */ private Font getFont() { return new Font("Fixedsys", Font.CENTER_BASELINE, 18); } /** * Get color */ private Color getRandColor(int fc, int bc) { if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc - 16); int g = fc + random.nextInt(bc - fc - 14); int b = fc + random.nextInt(bc - fc - 18); return new Color(r, g, b); } /** * Generating Random Pictures */ public void getRandcode(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); // The BufferedImage class is an Image class with buffers, and the Image class is a class for describing image information. BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics();// Graphics objects that generate Image objects can be changed to perform various rendering operations on images. g.fillRect(0, 0, width, height);//Picture size g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));//font size g.setColor(getRandColor(110, 133));//Font color // Drawing interference lines for (int i = 0; i <= lineSize; i++) { drowLine(g); } // Drawing random characters String randomString = ""; for (int i = 1; i <= stringNum; i++) { randomString = drowString(g, randomString, i); } logger.info(randomString); //Save the generated random string to session session.removeAttribute(RANDOMCODEKEY); session.setAttribute(RANDOMCODEKEY, randomString); g.dispose(); try { // Output the picture in memory to the client through the flow form ImageIO.write(image, "JPEG", response.getOutputStream()); } catch (Exception e) { logger.error("Failed to stream images from memory to client>>>> ", e); } } /** * Drawing strings */ private String drowString(Graphics g, String randomString, int i) { g.setFont(getFont()); g.setColor(new Color(random.nextInt(101), random.nextInt(111), random .nextInt(121))); String rand = String.valueOf(getRandomString(random.nextInt(randString .length()))); randomString += rand; g.translate(random.nextInt(3), random.nextInt(3)); g.drawString(rand, 13 * i, 16); return randomString; } /** * Drawing interference lines */ private void drowLine(Graphics g) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(13); int yl = random.nextInt(15); g.drawLine(x, y, x + xl, y + yl); } /** * Get random characters */ public String getRandomString(int num) { return String.valueOf(randString.charAt(num)); } }
This class doesn't need to be moved. It can be used directly.
2 page code
<!--html/bady Code--> <div > <div > <div > <input type="tel" id="verify_input" placeholder="Please enter the validation code" maxlength="4"> </div> </div> <div > <a href="javascript:void(0);" title="Click on Replace Verification Code"> <img id="imgVerify" src="login/getVerify" alt="Replacement of Verification Code" height="36" width="170" onclick="getVerify(this);"> </a> </div> <input type="button" onclick="aVerify()" value="Submission"> </div> </body> <!--js Code in--> <script type="text/javascript" src="./js/jquery.min.js"></script> <script> //Get the authentication code /*function getVerify(obj){ obj.src = "login/getVerify?"+Math.random();//Native js mode }*/ //Get the authentication code function getVerify() { // $("#imgCode").on("click", function() { $("#ImgVerify "). attr (" SRC ",'login / getVerify?'+ Math. random (); / / jQuery mode // }); } function aVerify(){ var value =$("#verify_input").val(); // alert(value); $.ajax({ async: false, type: 'post', url: 'login/checkVerify', dataType: "json", data: { verifyInput: value }, success: function (result) { if (result) { alert("success!"); } else { alert("failed!"); } // window.location.reload(); getVerify(); } }); } </script>
Note: There are two ways to get a picture of the authentication code.
3 Get code and verify code classes
@RestController @RequestMapping("/login") public class Picverifyaction { private final static Logger logger = LoggerFactory.getLogger(Picverifyaction.class); /** * Generating Verification Code */ @RequestMapping(value = "/getVerify") public void getVerify(HttpServletRequest request, HttpServletResponse response) { try { response.setContentType("image/jpeg");//Set the appropriate type and tell the browser to output pictures response.setHeader("Pragma", "No-cache");//Set up response header information to tell browsers not to cache this content response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expire", 0); RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil(); randomValidateCode.getRandcode(request, response);//Output Verification Code Picture Method } catch (Exception e) { logger.error("Failure to obtain authentication code>>>> ", e); } } /** * Check Verification Code */ @RequestMapping(value = "/checkVerify", method = RequestMethod.POST,headers = "Accept=application/json") public boolean checkVerify(@RequestParam String verifyInput, HttpSession session) { try{ //Getting random numbers from session s String inputStr = verifyInput; String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY"); if (random == null) { return false; } if (random.equals(inputStr)) { return true; } else { return false; } }catch (Exception e){ logger.error("Verification Code Failure", e); return false; } } }
4 effect map town building
5 source code
Of course, the above code is only the core part. If you have any problems, you can download it by yourself in github. charmsongo
If there is any better way, please leave a message.
Reference resources: https://blog.csdn.net/Colton_Null/article/details/78744240