类代码:
package com.yin; import javax.imageio.ImageIO; import javax.servlet.ServletException; 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; public class Image extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //浏览器3秒刷新1次 resp.setHeader("refresh","3"); //在内存中创建一个图片 BufferedImage image= new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB); //得到图片,一只2D的画笔 Graphics2D g=(Graphics2D)image.getGraphics(); //设置图片的背景颜色 g.setColor(Color.white); g.fillRect(0,0,80,20); //给图片写数据 g.setColor(Color.BLUE); g.setFont(new Font(null,Font.BOLD,20)); g.drawString(makeNum(),0,20); //告诉浏览器,这个请求用图片的方式打开 resp.setContentType("image/jpg"); //网站存在缓存,不让浏览器缓存 resp.setHeader("Cache-Control","no-cache"); resp.setHeader("Pragma","no-cache"); //吧图片写给浏览器 ImageIO.write(image,"jpg",resp.getOutputStream()); } private String makeNum(){ Random random=new Random(); String num=random.nextInt(999999)+""; StringBuffer sb=new StringBuffer(); for (int i = 0; i <7-num.length() ; i++) { sb.append("0"); } String s=sb.toString()+num; return num; } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); } }
web.xml中插入
<servlet> <servlet-name>image</servlet-name> <servlet-class>com.yin.Image</servlet-class> </servlet> <servlet-mapping> <servlet-name>image</servlet-name> <url-pattern>/img</url-pattern> </servlet-mapping>
显示结果;
标签:20,resp,javax,image,验证码,生成,new,import,Response From: https://www.cnblogs.com/insoon/p/17048508.html