SpringBoot实现验证码登录

一、编写验证码工具类

package com.lyancafe.material.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
* @author scy 2018/9/4
*/
public class VerifyUtil {
/**验证码字符集*/
private static final char[] chars = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
/**字符数量*/
private static final int SIZE = 4;
/**干扰线数量*/
private static final int LINES = 5;
/**宽度*/
private static final int WIDTH = 80;
/**高度*/
private static final int HEIGHT = 40;
/**字体大小*/
private static final int FONT_SIZE = 30;

/**
* 生成随机验证码及图片
* Object[0]:验证码字符串;
* Object[1]:验证码图片。
*/
public static Object[] createImage() {
StringBuffer sb = new StringBuffer();
// 1.创建空白图片
BufferedImage image = new BufferedImage(
WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
// 2.获取图片画笔
Graphics graphic = image.getGraphics();
// 3.设置画笔颜色
graphic.setColor(Color.LIGHT_GRAY);
// 4.绘制矩形背景
graphic.fillRect(0, 0, WIDTH, HEIGHT);
// 5.画随机字符
Random ran = new Random();
for (int i = 0; i <SIZE; i++) {
// 取随机字符索引
int n = ran.nextInt(chars.length);
// 设置随机颜色
graphic.setColor(getRandomColor());
// 设置字体大小
graphic.setFont(new Font(
null, Font.BOLD + Font.ITALIC, FONT_SIZE));
// 画字符
graphic.drawString(
chars[n] + "", i * WIDTH / SIZE, HEIGHT*2/3);
// 记录字符
sb.append(chars[n]);
}
// 6.画干扰线
for (int i = 0; i < LINES; i++) {
// 设置随机颜色
graphic.setColor(getRandomColor());
// 随机画线
graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),
ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
}
// 7.返回验证码和图片
return new Object[]{sb.toString(), image};
}

/**
* 随机取色
*/
public static Color getRandomColor() {
Random ran = new Random();
Color color = new Color(ran.nextInt(256),
ran.nextInt(256), ran.nextInt(256));
return color;
}
}

二、controller层使用

/**
* 登录
*/
@RequestMapping(value = "login")
@ResponseBody
public Map<Object, Object> login(String userName, String password, UserModel userModel, HttpSession session, HttpServletRequest request) {
String imageCode = (String) session.getAttribute("imageCode");
String code = request.getParameter("code");
userModel = userBo.findByNameAndPassword(userName, password);
HashMap<Object, Object> result = new HashMap<>(1);
if(imageCode.equalsIgnoreCase(code)){

if (userModel != null) {
result.put("result",true);
} else {
result.put("result",false);
}
}else{
result.put("result",false);
}
return result;
}

@ApiOperation("生成验证码")
@GetMapping("getCode")
public void getCode(HttpServletResponse response, HttpSession session) throws Exception{
//利用图片工具生成图片
//第一个参数是生成的验证码,第二个参数是生成的图片
Object[] objs = VerifyUtil.createImage();
//将验证码存入Session
session.setAttribute("imageCode",objs[0]);

//将图片输出给浏览器
BufferedImage image = (BufferedImage) objs[1];
response.setContentType("image/png");
OutputStream os = response.getOutputStream();
ImageIO.write(image, "png", os);
}

三、login.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>用户登录</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<link rel="stylesheet" type="text/css" href="<%=path%>css/login.css">
<script src="<%=path%>js/login.js"></script>
<script type="text/javascript" src="<%=path%>js/jquery.js"></script>
<script type="text/javascript" src="<%=path%>js/jquery-3.1.1.min.js"></script>
</head>

<body>
<div id="login_frame">
<h1>用户登录</h1>
<p id="image_logo"><img src="<%=path%>images/lyancafe.png"></p>
<form action="<%=basePath%>user/login" name="userForm">
<p><label class="label_input">用户名</label><input type="text" id="userName" class="text_field" placeholder="请输入账号"></p>
<p><label class="label_input">密码</label><input type="password" id="password" class="text_field"></p>
<p><label class="label_input">验证码</label><input type="text" id="code" class="text_field" placeholder="请输入验证码" autocomplete="off"></p>
<img src="<%=basePath%>user/getCode" alt="更改验证码" onclick="this.src='<%=basePath%>user/getCode?'+(new Date()).getTime();" />
<div id="login_control">
<input type="button" id="btn_login" value="登录" onclick="loginUser()">
<a href="<%=path%>user/index1">
<input type="button" id="btn_register" value="注册">
</a>
<a id="forget_pwd" href="<%=path%>user/forgetPassword">忘记密码?</a>
</div>
</form>
</div>
</body>
</html>

四、login.js

// 表单提交验证

function loginUser() {
var userName = $('#userName').val();
var password = $('#password').val();
var code=$("#code").val();
if (userName == '') {
alert('请输入用户名!');
return false;
}
if (password == '') {
alert('请输入密码!');
return false;
}
if (code == '') {
alert('请输入验证码!');
return false;
}
$.ajax({
type: "post",
url: "user/login",
data: {
userName: userName,
password: password,
code:code
},
dataType: "json",
success : function(data) {
console.log(data.result);
if(data.result){
alert("登录成功");
window.location.href="user/getAllUser";
} else if(data.result.false=0){
alert("请输入正确的账号和密码");
window.location.reload();
}else{
alert("验证码不正确");
window.location.reload();
}
},
error : function() {
alert("出错啦!!!")
}
});
}

五、页面展示

样式没有贴出来,可以自己设置,有什么不懂得随时问,如果回复不及时加QQ:501397578 验证码:孙创业



 

posted @ 2018-09-04 16:33  暖瞳123  阅读(1132)  评论(0编辑  收藏  举报