问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
package web.servlet;
import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet(value = "/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
static{
System.setProperty("java.awt.headless","true");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width = 100;
int height = 50;
//1.创建一个对象,在内存中存图片(验证码图片对象)
BufferedImage imge = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
//2.美化图片
//2.1 填充颜色
Graphics g = imge.getGraphics();//创建画笔对象
g.setColor(Color.pink);//设置画笔颜色
g.fillRect(0,0,width,height);//设置背景颜色
//2.2画边框
g.setColor(Color.BLUE);
g.drawRect(0,0,width-1,height-1);
String str = "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM1234567890";
//生成随机角标
StringBuffer sb = new StringBuffer();
Random ran = new Random();
for (int i = 1; i <=4; i++) {
int index = ran.nextInt(str.length());
//获取字符
char ch = str.charAt(index);
sb.append(ch);
//2.3写验证码
g.drawString(ch+"",width/5*i,height/2);
}
String session_code = sb.toString();
request.getSession().setAttribute("session_code",session_code);
request.removeAttribute("session_code");
//2.4画干扰线
g.setColor(Color.GREEN);
//生成随机坐标点
for (int i = 0; i < 10; i++) {
int x1 = ran.nextInt(width);
int x2 = ran.nextInt(width);
int y1 = ran.nextInt(height);
int y2 = ran.nextInt(height);
g.drawLine(x1,x2,y1,y2);
}
//3.将图片展示到页面
System.setProperty("java.awt.headless","true");
ImageIO.write(imge,"JPEG",response.getOutputStream());
// ImageIO.write(new CreateVerificationCodeImage(vericode).createImage(),"JPEG",resp.getOutputStream());
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
运行结果及报错内容
我的解答思路和尝试过的方法
-Djava.awt.headless=true加了这个也没用,有没有兄弟能帮忙解答一下