生成验证码
程序员文章站
2022-05-13 15:09:39
...
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/validcode")
public class ValidCodeServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//创建一张图片
//单位像素
BufferedImage image= new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB);
//创建画板,如果透明的玻璃
//想画板上画内容之前得设置画笔
Graphics2D gra = image.createGraphics();
gra.setColor(new Color(255, 255, 255));
gra.fillRect(0, 0, 200, 100);
List<Integer> randList = new ArrayList<Integer>();
Random random = new Random();
for(int i=0;i<4;i++) {
randList.add(random.nextInt(10));
}
Color[] colors = new Color[] {Color.BLUE, Color.CYAN, Color.GRAY,Color.GREEN,Color.ORANGE};
//字体 宋体,加粗、斜体,字号40
gra.setFont(new Font("宋体",Font.BOLD|Font.ITALIC,40));
for (int i=0;i<randList.size();i++) {
gra.setColor(colors[random.nextInt(colors.length)]);
gra.drawString(randList.get(i).toString(), i * 40 , 50 + (random.nextInt(21)-10));
}
for (int i=0;i<2;i++) {
gra.setColor(colors[random.nextInt(colors.length)]);
gra.drawLine(0,random.nextInt(100), 200, random.nextInt(100));
}
ServletOutputStream outputStream = resp.getOutputStream();
//工具类
ImageIO.write(image, "jpg", outputStream);
//把验证码放入到session中
HttpSession session = req.getSession();
session.setAttribute("code", ""+randList.get(0)+randList.get(1)+randList.get(2)+randList.get(3));
}
}
jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function(){
$("a").click(function(){
$("img").attr("src","validcode?date="+new Date());
return false;
})
})
</script>
</head>
<body>
<form action="login" method="post">
用户名: <input type="text" name="username"/><br/>
密 码: <input type="password" name="password"/><br/>
验证码:<input type="text" size="1" name="code"/><img src="validcode" width="80" height="40"/><a href="">看不清</a><br/>
<input type="submit" value="登录"/><input type="reset" value="重置">
</form>
</body>
</html>
下一篇: 链表实验-文件读取-增删改查