用户登录时,经常会使用到验证码,以下简单介绍一下验证码的实现过程。
1、用户登录jsp
<form action="<%=path%>/login/login.do" method="post">
<input name="username" id="username" onclick="$('#error').val('');" type="text" class="yhm"/>
<input name="password" type="password" id="password" onclick="$('#error').val('');" class="yhm pswd"/>
<input type="text" name="code" onclick="$('#error').val('');" class="yzhengm"/><img id="img1" title="点击获取新验证码" src="<%=path%>/verifycode/getVerifyCodeImage.do" onclick="changeimg()" width="62" height="28" alt="" style="display:inline-block;">
<input type="submit" class="dengl" value=""/>
</form>
上述页面中,点击验证码可更新changeimg()方法js实现如下
先要引入jquery-3.3.1.min.js、将随机字符转化成图片相关的DD_belatedPNG_0.0.8a-min.js。
然后在js代码块中需要引入DD_belatedPNG.fix('div, ul, img, li, input,p,ul,ol,h1,h2,h3,a,span,i');
<script type="text/javascript" src="<%=path %>/js/DD_belatedPNG_0.0.8a-min.js"></script>
<script type="text/javascript" src="<%=path %>/js/jquery-3.3.1.min.js"></script>
<script language="javascript" type="text/javascript">
function changeimg(){
var img=document.getElementById("img1");
//防止页面缓存
img.src="<%=path%>/verifycode/getVerifyCodeImage.do"+ "?r="+Math.random();
}
DD_belatedPNG.fix('div, ul, img, li, input,p,ul,ol,h1,h2,h3,a,span,i');
</script>
DD_belatedPNG_0.0.8a-min.js可在以下路径下载。
https://pan.baidu.com/s/1_gKOFhjuzKrCX4NSt67evQ
2、登录页面加载和点击验证码时,同时调用Controller类下的/verifycode/getVerifyCodeImage.do
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
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;
@Controller
@RequestMapping(value = "/verifycode")
public class VerifyCodeController {
/**
* Controller Method
*/
@RequestMapping(value = "/getVerifyCodeImage.do")
public void getVerifyCodeImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 设置验证码字符的字体和字号。
Font mFont = new Font("Arial Black", Font.PLAIN, 22);
//清除缓存,每次访问该页面时都从服务器端读取
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
// 设置验证码图片的长度和高度。
int width = 86, height = 40;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
//画图画板
Graphics g = image.getGraphics();
//定义一个随机数
Random random = new Random();
//设置画板背景颜色
// g.setColor(getRandColor(200, 250));
g.setColor(new Color(160, 177, 185));
//设置画板的填充范围
g.fillRect(1, 1, width - 1, height - 1);
// g.setColor(new Color(102, 102, 102));
g.drawRect(0, 0, width - 1, height - 1);
//设置字体
g.setFont(mFont);
//显示字符串,4位长度。
String sRand = "";
for (int i = 0; i < 4; i++) {
String tmp = getRandomChar();
sRand += tmp;
//设置每个数字的颜色
g.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110)));
//在画板上写数字,起始位置
g.drawString(tmp, 20 * i + 5, 27);
}
HttpSession session = request.getSession();
// 把验证码防到session中,用来前台对比。
session.setAttribute("verifycode", sRand.toLowerCase());
// System.out.println(sRand.toLowerCase()+"--------------------------》");
//显示图片
g.dispose();
//转换成一张图片,格式为JPEG
ImageIO.write(image, "JPEG", response.getOutputStream());
}
/**
* 随机获得颜色,RGB格式
*
* @param fc
* @param bc
* @return
*/
Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
private String getRandomChar() {
int rand = (int) Math.round(Math.random() * 2);
long itmp = 0;
char ctmp = '\u0000';
switch (rand) {
case 1:
itmp = Math.round(Math.random() * 25 + 65);
ctmp = (char) itmp;
return String.valueOf(ctmp);
case 2:
itmp = Math.round(Math.random() * 25 + 97);
ctmp = (char) itmp;
return String.valueOf(ctmp);
default:
itmp = Math.round(Math.random() * 9);
return String.valueOf(itmp);
}
}
}
上述实现类中,先随机生成一个四位数的随机数字+字母,然后将数字放到session中,最后使用ImageIO技术将随机字符转化成图片。
3、重点来了,用户登录时,需要校验用户输入的验证码是否与实际验证码一致
LoginController.class实现:
public String login(User user){
if(StringUtils.isEmpty(user.getUsername())){
request.setAttribute("error","用户名不能为空!");
return "index";
}
if(StringUtils.isEmpty(user.getPassword())){
request.setAttribute("error","密码不能为空!");
return "index";
}
String vcode =(String)request.getSession().getAttribute("verifycode");
if(!user.getCode().equalsIgnoreCase(vcode)){
request.setAttribute("error","验证码错误!");
return "index";
}
request.setAttribute("username",user.getUsername());
return loginService.checkUser(request,user);
}
上述loginService.checkUser()的实现可参考“SSM框架新增/修改用户、用户登录时密码加密处理及校验https://www.jianshu.com/p/d9773ec61661”一文。
网友评论