JavaWeb登陆验证之验证码模板
JavaWeb登陆验证时候的验证码模块
h5代码
<li>
<span class="login-input">验证码:</span>
<input type="text" class="input-con login-verify">
<img class="verify-img" src="/login/code">
<span id="verift-update">点击切换</span>
</li>
js代码
$(function () {
window.onload = function () {
//点击图片切换
//获取图片
$(".verify-img").click(function () {
let date = new Date().getTime();
$(this).attr("src","/login/code?date="+date);
})
$(".verift-update").click(function () {
let date = new Date().getTime();
$(".verify-img").attr("src","/login/code?date="+date);
})
}
})
servlet代码
@WebServlet("/Resureservlet")
public class CheckCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width =300;
int height= 100;
BufferedImage image =new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
//画笔对象
graphics.setColor(Color.red);
//设置画笔颜色
graphics.fillRect(0,0,width,height);
//填充一个蓝色的矩形 填充的位置和大小
graphics.setColor(Color.PINK);
//设置颜色
graphics.drawRect(0,0,width-1,height-1);
//画边框
graphics.setFont(new Font("宋体",Font.BOLD,25));
String str ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789"; //验证码包含的所有字符数字
StringBuffer sb= new StringBuffer();
Random random = new Random();
//画验证码验证符
for (int i = 1; i < 3; i++) {
int s = random.nextInt(str.length());
//随机获取字符串的角标,长度在字符串长度的范围内
char c = str.charAt(s);
//获取随机的字符
graphics.drawString(c+"",i*20,25);
//字符串的内容和位置
sb.append(c);
}
String checkCode = sb.toString();
HttpSession session = request.getSession();
//将验证码存储到session中,用于登录后的判断。
session.setAttribute("checkCode",checkCode);
//画干扰线
graphics.setColor(Color.black);
for (int i = 0; i < 3; i++) {
int x1 = random.nextInt(100);
int x2 = random.nextInt(100);
int y1 = random.nextInt(50);
int y2 = random.nextInt(50);
graphics.drawLine(x1,y1,x2,y2);
}
//将图片输入到页面展示
ImageIO.write(image,"jpg",response.getOutputStream());
//输出对象,后缀名,输出流输出
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}