package cn.ry.sevlet; 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("/YanZhengMaServlet") public class YanZhengMaServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); int width = 180; int height = 22; //创建buffefimage对象 BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //创建画笔 Graphics graphics = bufferedImage.getGraphics(); //设置画笔颜色 graphics.setColor(Color.white); //填充背景色 graphics.fillRect(0, 0, width, height); //创建随机对象random Random random = new Random(); //创建验证码的字符串 String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; // 设置字体 新罗马体 加粗 15+随机10的字体大小 Font font = new Font("Times New Roman", Font.BOLD, 15 + random.nextInt(5)); //创建stringBuffer对象进行 存入显示的验证码数据 StringBuffer stringBuffer = new StringBuffer(); for (int i = 1; i < 5; i++) { //随机获取s中的索引 int index = random.nextInt(s.length()); //利用索引 获取s中的单个字符 char c = s.charAt(index); //每次获取都将其存入到stringbuffer中 stringBuffer.append(c); //设置画笔颜色 每次都改变字体颜色 graphics.setColor(new Color(random.nextInt(150), random.nextInt(150), random.nextInt(150))); //设置字体 graphics.setFont(font); //将字符写入到图片上 graphics.drawString(c + "", width / 5 * i, height *2/3); } //设置干扰线 for (int i = 0; i < 4; i++) { int i1 = random.nextInt(width); int i2 = random.nextInt(height); int i3 = random.nextInt(width); int i4 = random.nextInt(height); graphics.setColor(new Color(random.nextInt(150), random.nextInt(150), random.nextInt(150))); //将干扰线存入图片中 graphics.drawLine(i1, i2, i3, i4); } //将其转换成string 类型 String s1 = stringBuffer.toString(); //将其存入到session域中 在之后在LoginServlet中与login.jsp中的输入框写入验证码进行比较 request.getSession().setAttribute("yanzhengma",s1); //最后将图片相应到页面上 ImageIO.write(bufferedImage,"jpeg",response.getOutputStream()); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
最后直接在想要出现的地方 jsp中写成这个样就可以了