servlet实现验证码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package org.tools; 2 import java.awt.Color; 3 import java.awt.Font; 4 import java.awt.Graphics; 5 import java.awt.image.BufferedImage; 6 import java.util.Random; 7 8 public class Image { 9 private BufferedImage image; 10 private String num; 11 private Image(){} 12 public BufferedImage getImage() { 13 return image; 14 } 15 public void setImage(BufferedImage image) { 16 this.image = image; 17 } 18 public String getNum() { 19 return num; 20 } 21 public void setNum(String num) { 22 this.num = num; 23 } 24 public static Image getnewImage(){ 25 int width=75,height=20; 26 Random rand=new Random(); 27 Image image=new Image(); 28 BufferedImage bim=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); 29 Graphics graph=bim.getGraphics(); 30 graph.setFont(new Font("宋体", Font.PLAIN, 18)); 31 graph.setColor(new Color(200,240,rand.nextInt(rand.nextInt(250-20)+20))); 32 graph.fillRect(0, 0, width, height); 33 34 String text=""; 35 for(int i=1;i<5;i++){ 36 String pint=""; 37 int n=rand.nextInt(91); 38 if(n>=65){ 39 text+=((char)n); 40 pint=(char)n+""; 41 }else{ 42 n=rand.nextInt(10); 43 text+=n; 44 pint=n+""; 45 } 46 graph.setColor(new Color(20+rand.nextInt(110),20+rand.nextInt(110),20+rand.nextInt(110))); 47 graph.drawString(pint, 15*i, 15); 48 } 49 graph.dispose(); 50 51 image.setImage(bim); 52 image.setNum(text); 53 return image; 54 } 55 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package org.tools; 2 3 import java.io.IOException; 4 5 import javax.imageio.ImageIO; 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 @SuppressWarnings("serial") 12 public class CheckNumServlet extends HttpServlet { 13 14 public void doGet(HttpServletRequest request, HttpServletResponse response) 15 throws ServletException, IOException { 16 this.doPost(request, response); 17 } 18 19 public void doPost(HttpServletRequest request, HttpServletResponse response) 20 throws ServletException, IOException { 21 Image image=Image.getnewImage(); 22 request.getSession().setAttribute("checkNum", image.getNum()); 23 ImageIO.write(image.getImage(), "JPEG", response.getOutputStream()); 24 } 25 26 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <servlet> 2 <servlet-name>CheckNumServlet</servlet-name> 3 <servlet-class>org.tools.CheckNumServlet</servlet-class> 4 </servlet> 5 6 <servlet-mapping> 7 <servlet-name>CheckNumServlet</servlet-name> 8 <url-pattern>/CheckNumServlet</url-pattern> 9 </servlet-mapping>
<img src="CheckNumServlet">