java 生成验证码的servlet类

本文介绍了一种使用Java Servlet生成包含随机数字的图形验证码的方法。该方法通过在内存中创建图像并利用Java AWT库绘制随机线条和字符来生成验证码。文章详细展示了如何设置图像属性、生成随机颜色及数字,并将验证码保存在session中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 生成验证码的servlet类

Java代码 复制代码 收藏代码
  1. import java.awt.Color;
  2. import java.awt.Font;
  3. import java.awt.Graphics;
  4. import java.awt.image.BufferedImage;
  5. import java.io.IOException;
  6. import java.io.OutputStream;
  7. import java.io.PrintWriter;
  8. import java.util.Random;
  9. import javax.imageio.ImageIO;
  10. import javax.servlet.ServletException;
  11. import javax.servlet.http.HttpServlet;
  12. import javax.servlet.http.HttpServletRequest;
  13. import javax.servlet.http.HttpServletResponse;
  14. import javax.servlet.http.HttpSession;
  15. import com.***.constant.Constant;
  16. public class ImageValidate extends HttpServlet {
  17. /**
  18. *
  19. */
  20. private static final long serialVersionUID = 2198678289097775859L;
  21. /**
  22. * Constructor of the object.
  23. */
  24. public ImageValidate() {
  25. super();
  26. }
  27. /**
  28. * Destruction of the servlet. <br>
  29. */
  30. public void destroy() {
  31. super.destroy(); // Just puts "destroy" string in log
  32. // Put your code here
  33. }
  34. private String name;
  35. /**
  36. * The doGet method of the servlet. <br>
  37. *
  38. * This method is called when a form has its tag value method equals to get.
  39. *
  40. * @param request
  41. * the request send by the client to the server
  42. * @param response
  43. * the response send by the server to the client
  44. * @throws ServletException
  45. * if an error occurred
  46. * @throws IOException
  47. * if an error occurred
  48. */
  49. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
  50. IOException {
  51. OutputStream outputStream = null;
  52. try {
  53. outputStream = response.getOutputStream();
  54. // 在内存中创建图象
  55. int width = 60, height = 20;
  56. BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  57. // 获取图形上下文
  58. Graphics g = image.getGraphics();
  59. // 生成随机类
  60. Random random = new Random();
  61. // 设定背景色
  62. g.setColor(getRandColor(200, 250));
  63. g.fillRect(0, 0, width, height);
  64. // 设定字体
  65. g.setFont(new Font("Times New Roman", Font.CENTER_BASELINE, 18));
  66. // 画边框
  67. // g.setColor(new Color());
  68. // g.drawRect(0,0,width-1,height-1);
  69. // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
  70. g.setColor(getRandColor(160, 200));
  71. for (int i = 0; i < 40; i++) {
  72. int x = random.nextInt(width);
  73. int y = random.nextInt(height);
  74. int xl = random.nextInt(12);
  75. int yl = random.nextInt(12);
  76. g.drawLine(x, y, x + xl, y + yl);
  77. }
  78. // 取随机产生的认证码(4位数字)
  79. String sRand = "";
  80. for (int i = 0; i < 4; i++) {
  81. String rand = String.valueOf(random.nextInt(10));
  82. sRand += rand;
  83. // 将认证码显示到图象中
  84. g
  85. .setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random
  86. .nextInt(110)));// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
  87. g.drawString(rand, 13 * i + 6, 16);
  88. }
  89. // 将认证码存入SESSION
  90. HttpSession session=request.getSession();
  91. session.setAttribute(Constant.LOGIN_VALIDATE_IMAGE, sRand);
  92. // 图象生效
  93. g.dispose();
  94. // 输出图象到页面
  95. ImageIO.write(image, "JPEG",outputStream);
  96. outputStream.flush();
  97. } catch (Exception e) {
  98. e.printStackTrace();
  99. }finally{
  100. outputStream.close();
  101. }
  102. }
  103. /**
  104. * 给定范围获得随机颜色
  105. *
  106. * @param fc
  107. * @param bc
  108. * @return
  109. */
  110. private static Color getRandColor(int fc, int bc) {
  111. Random random = new Random();
  112. if (fc > 255)
  113. fc = 255;
  114. if (bc > 255)
  115. bc = 255;
  116. int r = fc + random.nextInt(bc - fc);
  117. int g = fc + random.nextInt(bc - fc);
  118. int b = fc + random.nextInt(bc - fc);
  119. return new Color(r, g, b);
  120. }
  121. /**
  122. * The doPost method of the servlet. <br>
  123. *
  124. * This method is called when a form has its tag value method equals to
  125. * post.
  126. *
  127. * @param request
  128. * the request send by the client to the server
  129. * @param response
  130. * the response send by the server to the client
  131. * @throws ServletException
  132. * if an error occurred
  133. * @throws IOException
  134. * if an error occurred
  135. */
  136. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
  137. IOException {
  138. response.setContentType("text/html");
  139. PrintWriter out = response.getWriter();
  140. out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
  141. out.println("<HTML>");
  142. out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
  143. out.println(" <BODY>");
  144. out.print(" This is ");
  145. out.print(this.getClass());
  146. out.println(", using the POST method");
  147. out.println(" </BODY>");
  148. out.println("</HTML>");
  149. out.flush();
  150. out.close();
  151. }
  152. /**
  153. * Initialization of the servlet. <br>
  154. *
  155. * @throws ServletException
  156. * if an error occure
  157. */
  158. public void init() throws ServletException {
  159. // Put your code here
  160. }
  161. }
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.***.constant.Constant;


public class ImageValidate extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2198678289097775859L;
	/**
	 * Constructor of the object.
	 */
	public ImageValidate() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	private String name;
	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		
	    OutputStream outputStream = null;
	    
	    try {
	    	outputStream =  response.getOutputStream();
	     // 在内存中创建图象
	        int width = 60, height = 20;
	        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
	        // 获取图形上下文
	        Graphics g = image.getGraphics();
	        // 生成随机类
	        Random random = new Random();
	        // 设定背景色
	        g.setColor(getRandColor(200, 250));
	        g.fillRect(0, 0, width, height);
	        // 设定字体
	        g.setFont(new Font("Times New Roman", Font.CENTER_BASELINE, 18));
	        // 画边框
	        // g.setColor(new Color());
	        // g.drawRect(0,0,width-1,height-1);
	        // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
	        g.setColor(getRandColor(160, 200));
	        for (int i = 0; i < 40; i++) {
	            int x = random.nextInt(width);
	            int y = random.nextInt(height);
	            int xl = random.nextInt(12);
	            int yl = random.nextInt(12);
	            g.drawLine(x, y, x + xl, y + yl);
	        }
	        // 取随机产生的认证码(4位数字)
	        String sRand = "";
	        for (int i = 0; i < 4; i++) {
	            String rand = String.valueOf(random.nextInt(10));
	            sRand += rand;
	            // 将认证码显示到图象中
	            g
	                    .setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random
	                            .nextInt(110)));// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
	            g.drawString(rand, 13 * i + 6, 16);
	        }
	        // 将认证码存入SESSION
	        HttpSession session=request.getSession();
	        session.setAttribute(Constant.LOGIN_VALIDATE_IMAGE, sRand);
	        // 图象生效
	        g.dispose();
	        // 输出图象到页面
	        ImageIO.write(image, "JPEG",outputStream);
	        outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            outputStream.close();
        }
        
		

	}

	/**
	 * 给定范围获得随机颜色
	 * 
	 * @param fc
	 * @param bc
	 * @return
	 */
	private static Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the POST method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occure
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值