H5W3
当前位置:H5W3 > 其他技术问题 > 正文

servlet生成验证码图片

 

001 package com.rolia.learning.learningweb.validationcode;002003 /*004  * 创建日期 2006-7-23005  *006  * TODO 要更改此生成的文件的模板,请转至007  * 窗口 - 首选项 - Java - 代码样式 - 代码模板008  * 参数:009  * count:验证码的字符个数010  * width:验证码图片宽度011  * height:验证码图片高度012  * type:类型 0-纯数字 1-纯大写字母 2-数字和大学字母混合013  * 功能:生成验证码图片,将验证码保存进session里014  */015 import java.io.IOException;016017 import javax.servlet.ServletConfig;018 import javax.servlet.ServletException;019 import javax.servlet.http.HttpServlet;020 import javax.servlet.http.HttpServletRequest;021 import javax.servlet.http.HttpServletResponse;022023 import java.awt.*;024 import java.awt.image.*;025 import java.util.*;026 import javax.imageio.*;027 /**028  * @author Rolia029  *030  * TODO 要更改此生成的类型注释的模板,请转至031  * 窗口 - 首选项 - Java - 代码样式 - 代码模板032  */033 public class ValidationCodeServlet extends HttpServlet {034035     /**036    *037    */038   private static final long serialVersionUID = 1L;039   private final int TYPE_NUMBER = 0;040     private final int TYPE_LETTER = 1;041     private final int TYPE_MULTIPLE = 2;042     private int width;043     private int height;044     private int count;045     private int type;046     private String  validate_code;047     private Random random;048     private Font font;049     private int line;050051     @Override052   public void init(ServletConfig config) throws ServletException {053         super.init(config);054         width = 150;055         height = 50;056         count = 4;057         type = TYPE_NUMBER;058         random = new Random();059         line = 200;060     }061062     @Override063   protected void doGet(HttpServletRequest request,064             HttpServletResponse response) throws ServletException, IOException {065         response.setHeader(“Pragma”,”No-cache”);066         response.setHeader(“Cache-Control”,”no-cache”);067         response.setDateHeader(“Expires”, 0);068         response.setContentType(“image.jpeg”);069070         String reqCount = request.getParameter(“count”);071         String reqWidth = request.getParameter(“width”);072         String reqHeight = request.getParameter(“height”);073         String reqType = request.getParameter(“type”);074075         if(reqCount!=null && reqCount!=””)this.count = Integer.parseInt(reqCount);076         if(reqWidth!=null && reqWidth!=””)this.width = Integer.parseInt(reqWidth);077         if(reqHeight!=null && reqHeight!=””)this.height = Integer.parseInt(reqHeight);078         if(reqType!=null && reqType!=””)this.type = Integer.parseInt(reqType);079080         font = new Font(“Courier New”,Font.BOLD,width/count);081082         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);083084         Graphics g = image.getGraphics();085086         g.setColor(getRandColor(200,250));087         g.fillRect(0, 0, width, height);088089         g.setColor(getRandColor(160,200));090         for (int i=0;i<line;i++){091             int x = random.nextInt(width);092             int y = random.nextInt(height);093             int xl = random.nextInt(12);094             int yl = random.nextInt(12);095             g.drawLine(x,y,x+xl,y+yl);096         }097098         g.setFont(font);099         validate_code = getValidateCode(count,type);100         request.getSession().setAttribute(“validate_code”,validate_code);101         for (int i=0;i<count;i++){102             g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成103             int x = (int)(width/count)*i;104             int y = (int)((height+font.getSize())/2)-5;105             g.drawString(String.valueOf(validate_code.charAt(i)),x,y);106         }107108         g.dispose();109         ImageIO.write(image, “JPEG”, response.getOutputStream());110     }111112     @Override113   protected void doPost(HttpServletRequest request,114             HttpServletResponse response) throws ServletException, IOException {115         doGet(request, response);116     }117118     private Color getRandColor(int from,int to){119         Random random = new Random();120         if(to>255) from=255;121         if(to>255) to=255;122         int rang = Math.abs(to – from);123         int r=from+random.nextInt(rang);124         int g=from+random.nextInt(rang);125         int b=from+random.nextInt(rang);126         return new Color(r,g,b);127     }128129     private String getValidateCode(int size,int type){130         StringBuffer validate_code = new StringBuffer();131         for(int i = 0; i < size; i++){132             validate_code.append(getOneChar(type));133         }134         return validate_code.toString();135     }136     private String getOneChar(int type){137         String result = null;138         switch(type){139             case TYPE_NUMBER:140                 result = String.valueOf(random.nextInt(10));141                 break;142143             case TYPE_LETTER:144                 result = String.valueOf((char)(random.nextInt(26)+65));145                 break;146147             case TYPE_MULTIPLE:148                 if(random.nextBoolean()){149                     result = String.valueOf(random.nextInt(10));150                 }else{151                     result = String.valueOf((char)(random.nextInt(26)+65));152                 }153                 break;154             default:155                 result=null;156                 break;157         }158         if(result==null)throw new NullPointerException(“获取验证码出错”);159         return result;160     }161 }

 

web.xml

 <!– 生成图片验证码 –>  <servlet>   <servlet-name>validationcodeServlet</servlet-name>   <servlet-class>com.rolia.learning.learningweb.validationcode.ValidationCodeServlet</servlet-class>  </servlet><servlet-mapping>   <servlet-name>validationcodeServlet</servlet-name>   <url-pattern>/ValidateCodeServlet</url-pattern>  </servlet-mapping>validationcode_show.jsp

<!DOCTYPE HTML PUBLIC “-//w3c//dtd html 4.0 transitional//en”><html><head><title></title></head><body bgcolor=”#FFFFFF”><form action=”validationcode_heck.jsp” method=post><table align=center><tr><td>请输入验证码:<input type=’text’ name=’validate_code’ size=20></td><td><img src=”ValidateCodeServlet” width=150 height=50></td></tr><tr><td><input type=”submit” value=”提交”></td><td><input type=”reset” value=”重填”></td></tr></table></form></body></html>

validationcode_check.jsp:

<%@ page language=”java” contentType=”text/html; charset=UTF-8″    pageEncoding=”UTF-8″%><!DOCTYPE HTML PUBLIC “-//w3c//dtd html 4.0 transitional//en”><html><head><title>Lomboz JSP</title></head><body bgcolor=”#FFFFFF”>

<%String session_validate_code = (session.getAttribute(“validate_code”)).toString();if(session_validate_code==null)System.out.println(“validate code has not set”);else{ String request_code = request.getParameter(“validate_code”); if(request_code==null)out.println(“未输入”); else{  if(request_code.equalsIgnoreCase(session_validate_code))out.println(“匹配”);  else out.println(“不匹配”); }}%></body></html>

本文地址:H5W3 » servlet生成验证码图片

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址