67,515
社区成员
发帖
与我相关
我的任务
分享
//3.将验证码字符串存储到Session对象中
HttpSession session = request.getSession();
session.setAttribute("checkCode", checkCode);
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 javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/checkCodeServlet")
public class checkCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//创建checkCode变量存储验证码字符串
String checkCode = "";
//1.创建图片对象
int width = 80;
int height = 25;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//2.美化图片
Graphics g = image.getGraphics();//创建画笔对象
//2.1填充背景色
g.setColor(Color.PINK);
g.fillRect(0, 0, width, height);
//2.2画边框
g.setColor(Color.BLUE);
g.drawRect(0, 0, width - 1, height - 1);
//2.3写验证码
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random rm = new Random();
for (int i = 1; i <= 4; i++) {
int x = rm.nextInt(str.length());
String s = str.charAt(x) + "";
g.drawString(s, width / 5 * i, height / 3 * 2);
checkCode += s;
}
//2.4画干扰线
g.setColor(Color.green);
for (int i = 0; i < 30; i++) {
int x1 = rm.nextInt();
int x2 = rm.nextInt();
int y1 = rm.nextInt();
int y2 = rm.nextInt();
g.drawLine(x1, x2, y1, y2);
}
//3.将验证码字符串存储到Session对象中
HttpSession session = request.getSession();
session.setAttribute("checkCode", checkCode);
//4.将图片输出到页面上
ImageIO.write(image, "jpg", response.getOutputStream());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
<script>
window.onload=function () {
var image = document.getElementById("checkcodeimage");
image.onclick=function () {
var time = new Date().getTime();
image.src="/day1/checkCodeServlet?"+time;
}
}
</script>
<style type="text/css">
input{
margin-top: 5px;
}
.check input{
width: 50px;
}
.check img{
margin-top: 10px;
margin-left: 5px;
}
</style>
</head>
<body>
<form action="" method="post">
用户名:<input type="text" name="username" id="username"><br>
<span>密 码:</span><input type="password" name="password" id="password"><br>
<div class="check">
验证码:<input type="text" name="checkcode">
<img src="/day1/checkCodeServlet" id="checkcodeimage">
</div>
<br>
<input type="submit" value="登录">
</form>
</body>
</html>
您好,所以是什么问题呢,我的也是无法显示