请选择 进入手机版 | 继续访问电脑版

我爱学习网

 
查看: 8540|回复: 0

Java生成输出验证码图片,并进行验证

[复制链接]
发表于 2015-2-6 20:27:37 | 显示全部楼层 |阅读模式
Java生成输出验证码图片,并进行验证的代码。包含生成验证码,servlet输出验证码,验证验证码是否正确的代码。
此代码可以直接使用。
需要注意的是,调用验证码图片时,最好在url上加上时间戳参数,可避免刷新时由于缓存而不刷新验证码。

获取验证码图片,进行验证的 servlet代码。
  1. package org.houyong.test.servlet;

  2. import java.awt.Color;
  3. import java.awt.Font;
  4. import java.awt.Graphics;
  5. import java.awt.image.BufferedImage;
  6. import java.io.IOException;
  7. import java.io.PrintWriter;
  8. import java.util.Random;

  9. import javax.imageio.ImageIO;
  10. import javax.servlet.ServletException;
  11. import javax.servlet.ServletOutputStream;
  12. import javax.servlet.http.HttpServlet;
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpServletResponse;
  15. import javax.servlet.http.HttpSession;

  16. import org.houyong.test.common.RandomValidateCode;


  17. public class ValidateCode extends HttpServlet {

  18. /**
  19. * Constructor of the object.
  20. */
  21. public ValidateCode() {
  22. super();
  23. }

  24. /**
  25. * Destruction of the servlet.
  26. */
  27. public void destroy() {
  28. super.destroy(); // Just puts "destroy" string in log
  29. // Put your code here
  30. }

  31. /**
  32. * The doGet method of the servlet.
  33. *
  34. * This method is called when a form has its tag value method equals to get.
  35. *
  36. * @param request the request send by the client to the server
  37. * @param response the response send by the server to the client
  38. * @throws ServletException if an error occurred
  39. * @throws IOException if an error occurred
  40. */
  41. public void doGet(HttpServletRequest request, HttpServletResponse response)
  42. throws ServletException, IOException {
  43. this.doPost(request, response);
  44. }

  45. /**
  46. * The doPost method of the servlet.
  47. *
  48. * This method is called when a form has its tag value method equals to post.
  49. *
  50. * @param request the request send by the client to the server
  51. * @param response the response send by the server to the client
  52. * @throws ServletException if an error occurred
  53. * @throws IOException if an error occurred
  54. */
  55. public void doPost(HttpServletRequest request, HttpServletResponse response)
  56. throws ServletException, IOException {
  57. String action=request.getParameter("action");
  58. try {
  59. if(action.equals("getImgCode")){
  60. response.setContentType("image/jpeg");
  61.    response.setHeader("Pragma", "No-cache");
  62.    response.setHeader("Cache-Control", "no-cache");
  63.    response.setDateHeader("Expire", 0);
  64.    RandomValidateCode randomValidateCode = new RandomValidateCode();
  65.    try {
  66.        randomValidateCode.getRandcode(request, response);
  67.    } catch (Exception e) {
  68.        e.printStackTrace();
  69.    }
  70.    
  71. }else if(action.equals("validateCode")){
  72. PrintWriter out=null;
  73. try {
  74. request.setCharacterEncoding("utf-8");
  75. response.setContentType("text/html;charset=utf-8");
  76. out = response.getWriter();
  77. String inputCode=request.getParameter("inputCode");
  78. HttpSession session = request.getSession();
  79. String code=(String) session.getAttribute("RANDOMVALIDATECODEKEY");
  80. String returnStr="";
  81. if(inputCode.toUpperCase().equals(code.toUpperCase())){
  82. returnStr="success";
  83. }else{
  84. returnStr="failure";
  85. }
  86. out.print(returnStr);
  87. } catch (Exception e) {
  88. // TODO Auto-generated catch block
  89. e.printStackTrace();
  90. }finally{
  91. out.flush();
  92. out.close();
  93. }
  94. }else{
  95. response.sendRedirect("index.jsp");
  96. }
  97. } catch (Exception e) {
  98. // TODO Auto-generated catch block
  99. e.printStackTrace();
  100. response.sendRedirect("index.jsp");
  101. }

  102. }
  103. /**
  104. * Initialization of the servlet.
  105. *
  106. * @throws ServletException if an error occurs
  107. */
  108. public void init() throws ServletException {
  109. // Put your code here
  110. }

  111. }
复制代码



生成随机验证码图片的java代码
  1. package org.houyong.test.common;

  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. import javax.imageio.ImageIO;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. import javax.servlet.http.HttpSession;

  11. /*生成验证码*/
  12. public class RandomValidateCode {

  13.     public static final String RANDOMCODEKEY = "RANDOMVALIDATECODEKEY";//放到session中的key
  14.     private Random random = new Random();
  15.     private String randString = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ";//随机产生的字符串
  16.    
  17.     private int width = 80;//图片宽
  18.     private int height = 26;//图片高
  19.     private int lineSize = 20;//干扰线数量
  20.     private int stringNum = 4;//随机产生字符数量
  21.     /*
  22.      * 获得字体
  23.      */
  24.     private Font getFont(){
  25.         return new Font("Fixedsys",Font.CENTER_BASELINE,18);
  26.     }
  27.     /*
  28.      * 获得颜色
  29.      */
  30.     private Color getRandColor(int fc,int bc){
  31.         if(fc > 255)
  32.             fc = 255;
  33.         if(bc > 255)
  34.             bc = 255;
  35.         int r = fc + random.nextInt(bc-fc-16);
  36.         int g = fc + random.nextInt(bc-fc-14);
  37.         int b = fc + random.nextInt(bc-fc-18);
  38.         return new Color(r,g,b);
  39.     }
  40.     /**
  41.      * 生成随机图片
  42.      */
  43.     public void getRandcode(HttpServletRequest request,
  44.             HttpServletResponse response) {
  45.         HttpSession session = request.getSession();
  46.         //BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
  47.         BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
  48.         Graphics g = image.getGraphics();//产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
  49.         g.fillRect(0, 0, width, height);
  50.         g.setFont(new Font("Times New Roman",Font.ROMAN_BASELINE,18));
  51.         g.setColor(getRandColor(110, 133));
  52.         //绘制干扰线
  53.         for(int i=0;i<=lineSize;i++){
  54.             drowLine(g);
  55.         }
  56.         //绘制随机字符
  57.         String randomString = "";
  58.         for(int i=1;i<=stringNum;i++){
  59.             randomString=drowString(g,randomString,i);
  60.         }
  61.         session.removeAttribute(RANDOMCODEKEY);
  62.         session.setAttribute(RANDOMCODEKEY, randomString);
  63.         //System.out.println(randomString);
  64.         g.dispose();
  65.         try {
  66.             ImageIO.write(image, "JPEG", response.getOutputStream());//将内存中的图片通过流动形式输出到客户端
  67.         } catch (Exception e) {
  68.             e.printStackTrace();
  69.         }
  70.     }
  71.     /*
  72.      * 绘制字符串
  73.      */
  74.     private String drowString(Graphics g,String randomString,int i){
  75.         g.setFont(getFont());
  76.         g.setColor(new Color(random.nextInt(101),random.nextInt(111),random.nextInt(121)));
  77.         String rand = String.valueOf(getRandomString(random.nextInt(randString.length())));
  78.         randomString +=rand;
  79.         g.translate(random.nextInt(3), random.nextInt(3));
  80.         g.drawString(rand, 13*i, 16);
  81.         return randomString;
  82.     }
  83.     /*
  84.      * 绘制干扰线
  85.      */
  86.     private void drowLine(Graphics g){
  87.         int x = random.nextInt(width);
  88.         int y = random.nextInt(height);
  89.         int xl = random.nextInt(13);
  90.         int yl = random.nextInt(15);
  91.         g.drawLine(x, y, x+xl, y+yl);
  92.     }
  93.     /*
  94.      * 获取随机的字符
  95.      */
  96.     public String getRandomString(int num){
  97.         return String.valueOf(randString.charAt(num));
  98.     }
  99. }
复制代码
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回列表 返回顶部