💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
VerifyCodeServlet.java ~~~ package zyw.servlet; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; 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(name = "VerifyCodeServlet", urlPatterns = "/code") public class VerifyCodeServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int width=100; int height=30; String data="qwertyuiopasdfghjklzxcvbnm1234567890"; Random random=new Random(); // BufferedImage生成图片参数1-宽,参数2-高,参数3-类型 BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); Graphics graphics = image.getGraphics();//获取图片的绘图对象 graphics.setColor(Color.gray);//设置对象的颜色为灰色 graphics.fillRect(0, 0, width, height); //ImageIO这个类把图片输出给浏览器,write()把图片转成outputstream类型输出 //参数2-图片格式化的类型 //参数3-格式化的输出流 graphics.setColor(Color.black); for (int i = 0; i < 4; i++) { int position = random.nextInt(data.length());//随机生成位置 String randomStr = data.substring(position, position + 1);//取出位置对应的字符 graphics.drawString(randomStr, width / 5 * (i + 1), 15); } //ImageIO.write(image,"jpg",response.getOutputStream()); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.getOutputStream()); encoder.encode(image); } } ~~~ verifyCode.html ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> </body> <center> <h2>切换验证码</h2> <script> function changeImageCode() { document.getElementById('btn').isDisabled=true; document.getElementById('identity').src='code?ts='+new Date().getTime(); } </script> <image src="code" id="identity" onload="btn.disable=false;" style="cursor:pointer; vertical-align:middle"> </image> <input type="button" value="看不清,更换验证码" onclick="changeImageCode()" id="btn" style="vertical-align:middle"> </center> </html> ~~~ ![](https://box.kancloud.cn/6401ad92a9f0295c8c5eba6534804854_1075x202.png)