登陆的时候有的需要带验证码连同用户名密码一同发送到后台校验,用户名和密码的校验我这个demo里面就不处理了,为了突出验证码部分,所以直接看验证码的校验就可以,验证通过控制台打印“用户输入的验证码和图片生成的验证码相等,登陆成功”。
JSP页面代码
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML> <html lang="en"> <head> <title>登录界面</title> <script type="text/javascript" src="${pageContext.request.contextPath}/static/jquery/jquery-1.9.1.min.js"></script> <script src="${pageContext.request.contextPath}/static/bootstrap-3.3.5/js/bootstrap.min.js"></script> <link rel="stylesheet" href="${pageContext.request.contextPath}/static/bootstrap-3.3.5/css/bootstrap-theme.css"></link> <link rel="stylesheet" href="${pageContext.request.contextPath}/static/bootstrap-3.3.5/css/bootstrap.css" type="text/css"></link> </head> <body> <div class="login-content"> <div class="login-title"> <h1>登录</h1> </div> <div class="login"> <form> <!-- <div> <div> <input id="username" type="text" name="username" placeholder="用户名" /> </div> </div> <div> <div> <input id="pwd" type="password" name="password" placeholder="密码" /> </div> </div> --> <div> <input type="text" id="user_input_verifyCode" name="user_input_verifyCode" placeholder="验证码" maxlength="4"> <span class="code_img"> <img src="${pageContext.request.contextPath }/login/getVerifyCode" width="110" height="40" id="verifyCodeImage"> </span> <span> <a id="changeVerifImageRegister" onclick="javascript:changeImage();">换一张</a> </span> </div> <input id="submit" type="button" value="登录" onclick="login()"> </form> </div> </div> <script type="text/javascript"> function genTimestamp() { var time = new Date(); return time.getTime(); } function changeImage() { $('#verifyCodeImage').attr('src', '${pageContext.request.contextPath }/login/getVerifyCode?timestamp=' + genTimestamp()); } //登录,目前只检测验证码 function login(){ var user_input_verifyCode=$("#user_input_verifyCode").val(); $.ajax({ type : 'post', url : "${pageContext.request.contextPath}/login/login", data:{verifyCode:user_input_verifyCode}, //dataType : "json", success : function(data) { }, error : function() { alert("查询失败"); } }); } </script> </body> </html>
Controller代码:注意的是,当访问登录界面的时候就会自动加载验证码图片,同时把验证码值存入session中,当我们处理登录逻辑的时候是通过前端输入的验证码值和从session中存储的图片中的验证码值来进行比较进行校验的。
package com.wonders.controller; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.font.FontRenderContext; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; /** * 登录功能 */ @Controller @RequestMapping("/login") public class LoginController { // http://localhost:8080/ssmmaven/login/showLoginView @RequestMapping("/showLoginView") public ModelAndView getIndex() { ModelAndView mv = new ModelAndView(); mv.setViewName("login"); return mv; } /** * 获取验证码 * * @param response * @param session */ @RequestMapping("/getVerifyCode") public void generate(HttpServletResponse response, HttpSession session) { ByteArrayOutputStream output = new ByteArrayOutputStream(); String verifyCodeValue = drawImg(output); session.setAttribute("verifyCodeValue", verifyCodeValue); try { ServletOutputStream out = response.getOutputStream(); output.writeTo(out); } catch (IOException e) { e.printStackTrace(); } } /** * 绘画验证码 * * @param output * @return */ private String drawImg(ByteArrayOutputStream output) { String code = ""; // 随机产生4个字符 for (int i = 0; i < 4; i++) { code += randomChar(); } int width = 70; int height = 25; BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); Font font = new Font("Times New Roman", Font.PLAIN, 20); // 调用Graphics2D绘画验证码 Graphics2D g = bi.createGraphics(); g.setFont(font); Color color = new Color(66, 2, 82); g.setColor(color); g.setBackground(new Color(226, 226, 240)); g.clearRect(0, 0, width, height); FontRenderContext context = g.getFontRenderContext(); Rectangle2D bounds = font.getStringBounds(code, context); double x = (width - bounds.getWidth()) / 2; double y = (height - bounds.getHeight()) / 2; double ascent = bounds.getY(); double baseY = y - ascent; g.drawString(code, (int) x, (int) baseY); g.dispose(); try { ImageIO.write(bi, "jpg", output); } catch (IOException e) { e.printStackTrace(); } return code; } /** * 随机参数一个字符 * * @return */ private char randomChar() { Random r = new Random(); String s = "ABCDEFGHJKLMNPRSTUVWXYZ0123456789"; return s.charAt(r.nextInt(s.length())); } /** * 登录逻辑 */ @RequestMapping("/login") public void login(HttpServletRequest request, HttpSession session) { String inputVerifyCode=request.getParameter("verifyCode"); System.out.println("用户输入的验证码值------>" + inputVerifyCode); String verifyCodeValue=(String) session.getAttribute("verifyCodeValue"); System.out.println("Session中的验证码值------>" + verifyCodeValue); if(verifyCodeValue.equals(inputVerifyCode.toUpperCase())){ System.out.println("用户输入的验证码和图片生成的验证码相等,登陆成功"); } } }
效果如下: