1. Create a tool class to generate pictures
package com.bishe.utli; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.util.Random; public class ImageVerificationCode { private int weight = 100; //Length and width of captcha image private int height = 40; private String text; //The text content used to save the verification code private Random r = new Random(); //Get random number object //private String[] fontNames = {"Tahoma", "Chinese Kaiti", "bold", "Microsoft YaHei", "Kaiti ﹣ GB2312"}; / / font array //Font array private String[] fontNames = {"Georgia"}; //Verification code array private String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ"; /** * Get random colors * * @return */ private Color randomColor() { int r = this.r.nextInt(225); //Why is 225 here? Because when r, g, and b are all 255, they are white. In order to be recognizable, they need to be darker. int g = this.r.nextInt(225); int b = this.r.nextInt(225); return new Color(r, g, b); //Returns a random color } /** * Get random font * * @return */ private Font randomFont() { int index = r.nextInt(fontNames.length); //Get random fonts String fontName = fontNames[index]; int style = r.nextInt(4); //Get the style of the font randomly, 0 is no style, 1 is bold, 2 is italics, 3 is bold and italics int size = r.nextInt(10) + 24; //Get font size at random return new Font(fontName, style, size); //Returns a random font } /** * Get random characters * * @return */ private char randomChar() { int index = r.nextInt(codes.length()); return codes.charAt(index); } /** * Draw interference lines to prevent the computer from analyzing pictures * * @param image */ private void drawLine(BufferedImage image) { int num = r.nextInt(10); //Define the number of interference lines Graphics2D g = (Graphics2D) image.getGraphics(); for (int i = 0; i < num; i++) { int x1 = r.nextInt(weight); int y1 = r.nextInt(height); int x2 = r.nextInt(weight); int y2 = r.nextInt(height); g.setColor(randomColor()); g.drawLine(x1, y1, x2, y2); } } /** * How to create a picture * * @return */ private BufferedImage createImage() { //Create picture buffer BufferedImage image = new BufferedImage(weight, height, BufferedImage.TYPE_INT_RGB); //Get brush Graphics2D g = (Graphics2D) image.getGraphics(); //Set background color random g.setColor(new Color(255, 255, r.nextInt(245) + 10)); g.fillRect(0, 0, weight, height); //Return to a picture return image; } /** * How to get the picture of verification code * * @return */ public BufferedImage getImage() { BufferedImage image = createImage(); Graphics2D g = (Graphics2D) image.getGraphics(); //Get brush StringBuilder sb = new StringBuilder(); for (int i = 0; i < 4; i++) //Just draw four characters { String s = randomChar() + ""; //Randomly generate characters. Because there is only the method of drawing strings, there is no method of drawing characters, so you need to change the characters into strings and draw again sb.append(s); //Add to StringBuilder float x = i * 1.0F * weight / 4; //Define the x coordinate of the character g.setFont(randomFont()); //Set font, random g.setColor(randomColor()); //Set color, random g.drawString(s, x, height - 5); } this.text = sb.toString(); drawLine(image); return image; } /** * How to get the text of verification code * * @return */ public String getText() { return text; } public static void output(BufferedImage image, OutputStream out) throws IOException //How to write out the verification code picture { ImageIO.write(image, "JPEG", out); } }
2. Add a codeController to the controller layer
package com.bishe.user.controller; import com.bishe.utli.ImageVerificationCode; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.IOException; @Controller @RequestMapping("/code") public class codeController { @RequestMapping("verify") @ResponseBody public void getVerifiCode(HttpServletRequest request, HttpServletResponse response) throws IOException, IOException { /* 1.Generate verification code 2.Store the text on the verification code in the session 3.Send the captcha picture to the client */ ImageVerificationCode ivc = new ImageVerificationCode(); //Use our verification code class to generate verification code class objects BufferedImage image = ivc.getImage(); //Get verification code request.getSession().setAttribute("text", ivc.getText()); //Store the text of the verification code in the session ivc.output(image, response.getOutputStream());//Respond the captcha picture to the client } }
(generate the picture and save the verification code in the session)
3. Web page code
Display of verification code
<span style="position: absolute"> <img id="img" onclick="getVerifiCode()" title="Click to refresh the verification code" src="${pageContext.request.contextPath}/code/verify"/> </span></td>
Write the event and click the picture to refresh the verification code
function getVerifiCode() { $("#img").prop('src','${pageContext.request.contextPath}/code/verify?a='+new Date().getTime()); }
Write this to test that the verification code has taken effect, and then write the verification process
1. Write submit function
2. Use asynchronous request
function login() { var username = $("#username").val(); var password = $("#password").val(); var code = $("#code").val(); $.ajax({ type:"post", url:"${pageContext.request.contextPath}/user/login", data:{"username":username,"password":password,"code":code}, success:function(message){ if(message==1){ getVerifiCode(); alert("Username or password incorrect "); }else if(message==2){ getVerifiCode(); alert("Verification code error"); }else if(message==3){ alert("Landing successfully") } } }); }
3. Write controller layer
@RequestMapping(value = "/login",method = RequestMethod.POST) @ResponseBody public String login(user u, String code, HttpSession session, RedirectAttributes redirectAttributes){ String text = (String)session.getAttribute("text"); System.out.println(text); System.out.println(u); //Remove the verification code in the session immediately after it is taken out session.removeAttribute("text"); //Ignore case validation if(code.equalsIgnoreCase(text)){ //If you think you're right, verify your username and password user us = userService.getEmploye(u); if(us==null){ redirectAttributes.addFlashAttribute("msg","Wrong user name or password"); return "1"; }else{ session.setAttribute("loginUser",us); } }else{ //If you want to take the error message to the page when redirecting redirectAttributes.addFlashAttribute("msg","Verification code error"); return "2"; } return "3"; }
(the pojo object is used to receive data, and the information of the verification code exists in the session, so a session object is passed in to get it.)
4. Write service layer code
public user getEmploye(user u) { userExample example = new userExample(); userExample.Criteria criteria = example.createCriteria(); criteria.andUsernameEqualTo(u.getUsername()); criteria.andPasswordEqualTo(u.getPassword()); List<user> employees = userMapper.selectByExample(example); if(employees.size()>0){ return employees.get(0); } return null; }
(functions generated by reverse engineering are used)