验证码的技术提供来源于JDK
一、了解web请求
-
当启动服务后,服务器遇到img静态资源会产生两个请求
-
①首先发送资源路径到服务器
②服务器以字节流的形式返回回来就成了我们所看到的图片
二、需求结果
三、代码示例
// 注释帮你理解
Login.jsp界面
// An highlighted block
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>数字随机验证码</title>
</head>
<style type="text/css">
body{
width: 400px;
height: 400px;
margin: auto;
}
</style>
<script type="text/javascript" src="js/jquery-1.12.4.js"></script>
<script type="text/javascript">
$(function () {
$("a").click(function () {
//浏览器自带缓存功能 不会重新请求同一个结果
$("img").attr("src","validServlet?data="+new Date())
return false;
})
})
</script>
<body>
<form method="get" action="#">
<h1>登录</h1>
账号:<input type="text"/><br/>
密码:<input type="password"/><br/>
验证码:<input type="text" size="1"/><img src="validServlet" width="80px" height="40" /><a href="#">看不清</a>
</form>
</body>
</html>
下面展示一些 内联代码片
。
// 注释爱你么么哒
验证码的Servlet代码
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//首先创建一张图片 单位像素 BufferedImage.TYPE_3BYTE_BGR :蓝色,绿色和红色以3个字节存储。
BufferedImage image=new BufferedImage(200,100,BufferedImage.TYPE_3BYTE_BGR);
//在图片上 创建画板
Graphics gpi=image.createGraphics();
//设置画笔颜色
gpi.setColor(Color.white);
//把背景涂成白色 从坐标原点开始填充
gpi.fillRect(0,0,200,100);
//设置数字集合 以字符串类型储存
List<String> list=new ArrayList<String>();
//创建随机类
Random random=new Random();
//随机生成4个随机数并且储存
for (int i=0;i<4;i++){
//随机产生0-10的随机数 不包含10
list.add(random.nextInt(10)+"");
}
//随机数字颜色集合
Color[] colors={Color.BLUE,Color.blue,Color.GREEN,Color.RED};
//设置字体样式
gpi.setFont(new Font("宋体",Font.BOLD|Font.ITALIC,35));
//一个一个的字涂上图片
for (int i=0;i<list.size();i++){
//随机一种画笔色彩
gpi.setColor(colors[random.nextInt(4)]);
//把数字画上画板 以动态坐标移动 每个字间隔40px 上下浮动20px
gpi.drawString(list.get(i),i*40,50+random.nextInt(41)-20);
}
//设置两条干扰线
for (int i=0;i<2;i++){
gpi.setColor(colors[random.nextInt(4)]);
gpi.drawLine(0,random.nextInt(51),200,(int)(Math.random()*50+51));
}
//创建输出流
ServletOutputStream os=resp.getOutputStream();
//以流形式保存图片
ImageIO.write(image,"jpg",os);
//创建session对象保存随机数字
HttpSession session=req.getSession();
//以字符串保存
session.setAttribute("code",""+list.get(0)+list.get(1)+list.get(2)+list.get(3));
}
四、更深了解,请参考JDKapi
下载地址–>官方网站