java实现图片验证码
短信预约 -IT技能 免费直播动态提醒
本文实例为大家分享了java实现图片验证码的具体代码,供大家参考,具体内容如下
目的:
1) 验证操作者是否是人
2) 防止表单重复提交
生成验证码的要点:
1) 使用java代码生成图片对象
BufferedImage
2) 使用Random生成随机字符串
3) 将图片对象用
ImageIO.write(图片对象, "jpeg|png", 响应字节输出流)
返回给客户端浏览器
验证验证码:
要点:
1) 将验证码文字存入session作用域
2) 表单提交时,对比session中的验证码和表单中的验证码
CaptchaUtils.java
package cn.seeker.utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.List;
public class CaptchaUtil {
public static String [] fuhao = {"+","-","*","/"};
public static int num = 0;
//生成随机算式
public static String random(){
List list = new ArrayList();
Random ran = new Random();
int n1 = ran.nextInt(10);
int n2 = ran.nextInt(10);
String f = fuhao[ran.nextInt(fuhao.length)];
StringBuilder sb = new StringBuilder(4);
switch (f){
case "+":
num = n1+n2;
break;
case "-":
num =n1-n2;
break;
case "*":
num = n1*n2;
break;
case "/":
if(n2 == 0){
n2 = ran.nextInt(10)+1;
num = n1/n2;
}else{
num = n1/n2;
}
break;
}
sb.append(n1);
sb.append(f);
sb.append(n2);
sb.append("=");
return sb.toString();
}
public static void outputImage(String str, OutputStream os){
Random ran = new Random();
//创建图片对象
BufferedImage img = new BufferedImage(100,40, BufferedImage.TYPE_INT_RGB);
//获取画布
Graphics g = img.getGraphics();
//设置背景
g.setColor(Color.white);
g.fillRect(0,0,100,40);
//写字
g.setColor(Color.black);
g.setFont(new Font("微软雅黑",Font.PLAIN,30));
g.drawString(str,10,40);
//随机三条线
g.drawLine(ran.nextInt(100),ran.nextInt(40),
ran.nextInt(100),ran.nextInt(40));
g.drawLine(ran.nextInt(100),ran.nextInt(40),
ran.nextInt(100),ran.nextInt(40));
g.drawLine(ran.nextInt(100),ran.nextInt(40),
ran.nextInt(100),ran.nextInt(40));
// 4. 输出结果
// 常见的压缩格式:jpeg(有损压缩), png(无损压缩) ...
try {
ImageIO.write(img, "png", os);
} catch (IOException e) {
e.printStackTrace();
}
}
}
regist.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2018/10/14
Time: 15:43
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册</title>
<style>
img { cursor: pointer}
</style>
</head>
<body>
<form action="/regist" method="post">
<img class="lazy" data-src="/captcha.png" onclick="changeImg(this)">
输入验证码:<input type="text" name="cap">
<input type="submit" value="提交">
</form>
<script>
function changeImg(img) {
// 浏览器有一个缓存特性,
// 第一次从服务器获取图片,浏览器第二次发送请求时发现地址没有改变,就会使用第一次的图片,而不会真正发送请求
// 为了让浏览器每次都把请求发送给服务器,给一个时间参数
img.class="lazy" data-src = "/captcha.png?t="+new Date().getTime(); // 给class="lazy" data-src赋一个新值,就会向新值的地址发送一次请求
}
</script>
</body>
</html>
CaptchaServlet.java
package cn.seeker.controller;
import cn.seeker.utils.CaptchaUtil;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = "/captcha.png")
public class CaptchaServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("image/png");
//获取随机字符串
String random = CaptchaUtil.random();
//输出图片
CaptchaUtil.outputImage(random,response.getOutputStream());
//存入结果
request.getSession().setAttribute("res",CaptchaUtil.num);
}
}
registServlet.jsp
package cn.seeker.controller;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = "/regist")
public class registServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String cap = req.getParameter("cap");
Integer res = (Integer)req.getSession().getAttribute("res");
if(Integer.parseInt(cap) == res) {
// 填写正确,注册成功
req.getSession().removeAttribute("res");
System.out.println("注册成功");
resp.sendRedirect("/index.jsp");
} else {
req.setAttribute("error", "验证码不正确");
req.getRequestDispatcher("/jsp/regist.jsp").forward(req,resp);
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341