前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
var img= document.getElementById("changImg");
img.onclick=function () {
img.src="/tomcat_day01/checkCode?"+new Date.getTime();
}
</script>
</head>
<body>
<img id="changImg" src="/tomcat_day01/checkCode">
</body>
</html>
package cn.wjs.servlet;
import javax.imageio.ImageIO;
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.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
/**
* 验证码类实现
*/
@WebServlet("/checkCode")
public class CheckCode extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width=100;
int height=50;
//验证码图片对象
BufferedImage bufferedImage=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//填充图片背景色
Graphics graphics=bufferedImage.getGraphics();
graphics.setColor(Color.pink);
graphics.fillRect(0,0,width,height);
//设置图片边框
graphics.setColor(Color.blue);
graphics.drawRect(0,0,width-1,height-1);
//写验证码
String code= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
Random rdm=new Random();
graphics.setFont(new Font("TimesRoman",Font.BOLD,20));
graphics.setColor(Color.BLACK);
for (int i =1; i <=4 ; i++) {
int i1 = rdm.nextInt(code.length());
char c = code.charAt(i1);
graphics.drawString(c+"",width/5*i,height/2);
}
//写干扰线
graphics.setColor(Color.MAGENTA);
for (int i = 0; i <10 ; i++) {
int x1=rdm.nextInt(width);
int y1=rdm.nextInt(height);
int x2=rdm.nextInt(width);
int y2=rdm.nextInt(height);
graphics.drawLine(x1,y1,x2,y2);
}
//将图片输出到浏览器
ImageIO.write(bufferedImage,"jpg",response.getOutputStream());
}
}
本文介绍了一种使用Java Servlet生成验证码的方法,包括前端页面与后端逻辑。前端通过HTML与JavaScript实现验证码刷新功能;后端通过Servlet创建带随机字符和干扰线的图片。
153

被折叠的 条评论
为什么被折叠?



