1.情境還原
最近在項目的前端工程中,有這樣的需求:隨機產生驗證碼,點擊圖片驗證碼也可以更換驗證碼,並且傳輸到後台驗證。 效果UI圖:
2.實現方案 1.前端介面布置代碼:
<div class="checkCode" style="padding: 5px 0px 10px; position: relative;"> <INPUT name="checkcode" class="ipt" id="image1" type="text" placeholder="請輸入驗證碼" value=""> <img src="http://localhost:8080/ImageChack" id="image2" border="" class="verifyimg" height="30px" width="120 px" onClick="this.src='http://localhost:8080/ImageChack?redirect='+Math.random()"/></div>
圖片驗證碼的點擊方法(更換驗證碼)
onClick="this.src='http://localhost:8080/ImageChack?redirect='+Math.random()"
2.隨機產生驗證碼的的servlet:
public class ImageChack extends HttpServlet { private static final long serialVersionUID = 1L; private Font getFont(){ Random random = new Random(); Font[] font = new Font[5]; font[0] = new Font("Ravie", Font.PLAIN, 24); font[1] = new Font("Antique Olive Compact", Font.PLAIN, 24); font[2] = new Font("Forte", Font.PLAIN, 24); font[3] = new Font("Wide Latin", Font.PLAIN, 24); font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, 24); return font[random.nextInt(5)]; } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //設定回應標頭資訊 response.setContentType("image/jpeg"); //指定頁面不緩衝 response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "No-cache"); response.setDateHeader("Expires", 0); //擷取輸出資料流 OutputStream os = response.getOutputStream(); //指定寬高 int width = 120,height = 30; //指定寬高和bufferedImage對象 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //畫筆畫在image 上 Graphics g = image.getGraphics(); Color c = g.getColor(); g.fillRect(0, 0, width, height); char[] ch = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz23456789".toCharArray(); int len = ch.length; String res = ""; Random random = new Random(); for(int i=0; i<5; i++){ //設定字型 g.setFont(getFont()); String rand = new Character(ch[random.nextInt(len)]).toString(); res+=rand; //設定隨機顏色 g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255))); g.drawString(rand, 20*i+6, 25); } //產生幹擾點// for(int i=0; i<6; i++){// int x1 = random.nextInt(width);// int y1 = random.nextInt(height);// g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));// g.drawOval(x1, y1, width, height);// } //將畫筆顏色還原 g.setColor(c); g.dispose(); //將驗證碼儲存到session request.getSession().setAttribute("imageChack", res); System.out.println(res.toLowerCase()); //輸出映像 ImageIO.write(image, "JPEG", os); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }} 3.在web.xml中配置ImageChack
<!--初始化圖片驗證servlet--><servlet> <servlet-name>ImageChack</servlet-name> <servlet-class>org.yxm.cms.controller.ImageChack</servlet-class></servlet><servlet-mapping> <servlet-name>ImageChack</servlet-name> <url-pattern>/ImageChack</url-pattern></servlet-mapping>
4.在loginController的代碼邏輯:
@RequestMapping(value = "/login", method = RequestMethod.POST)public String login(@RequestParam String username, @RequestParam String password, Model model, HttpServletRequest request) { User user = userService.findByUserNamePassword(username, password); //使用者輸入 String inputStr = request.getParameter("checkcode"); //隨機碼產生 String picStr = (String) request.getSession().getAttribute("imageChack"); System.out.print("使用者輸入"+inputStr); System.out.print("隨機碼產生"+picStr); if (user == null) { model.addAttribute("login_error", "登入名稱或密碼錯誤。"); return "login/login"; } if(!inputStr.equals(picStr)){ model.addAttribute("verfied_error", "圖片驗證碼輸入有錯。"); return "login/login"; } List<Permission> permissions = userService.listUserPermissions(user.getId()); List<Integer> gids = userService.listUserGids(user.getId()); List<Permission> groupPermissions = groupService.listGroupsPermissions(ListUtil.list2array(gids)); for (Permission p : groupPermissions) { if (!permissions.contains(p)) { permissions.add(p); } } request.getSession().setAttribute(Constant.LOGIN_USER, user); request.getSession().setAttribute(Constant.LOGIN_PERMISSIONS, permissions); return "redirect:/admin/index";}