zoukankan      html  css  js  c++  java
  • javaweb登录验证码的实现

    第一种

      第一步:  JSP

        <li><input name="validCode"  id="validCode" type="text" class="loginvalid" value="" onclick="JavaScript:this.value=''"/><img src="${path}/patchca.htm"  id = "patchca" style="display:inline-block; float:right;100px; height:48px;line-height:48px;margin-right:100px;padding:0;"></li>

      第二步: 后台

        @RequestMapping("/patchca.htm")
        public void patchca(HttpServletResponse response,HttpSession session) throws IOException
        {
          CaptchaService cs = new CaptchaService();
          response.setContentType("image/png");
          response.setHeader("cache", "no-cache");
          OutputStream os = response.getOutputStream();
          String patchca = EncoderHelper.getChallangeAndWriteImage(cs, "png", os);
          session.setAttribute("PATCHCA", patchca);
          os.flush();
          os.close();
          cs = null;
        }

    第二种 

      

    Controller:生成验证码

    [java] view plain copy
     
     print?
    1. @RequestMapping("/user/check.jpg")  
    2.     public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {  
    3.         // 通知浏览器不要缓存  
    4.         response.setHeader("Expires", "-1");  
    5.         response.setHeader("Cache-Control", "no-cache");  
    6.         response.setHeader("Pragma", "-1");  
    7.         CaptchaUtil util = CaptchaUtil.Instance();  
    8.         // 将验证码输入到session中,用来验证  
    9.         String code = util.getString();  
    10.         request.getSession().setAttribute(“code”, code);  
    11.         // 输出打web页面  
    12.         ImageIO.write(util.getImage(), "jpg", response.getOutputStream());  
    13.     }  


    jsp:显示验证码

    [java] view plain copy
     
     print?
    1. <img id="img" src="<%=basePath%>user/check.jpg" onclick="refresh()">  
    [java] view plain copy
     
     print?
    1. function refresh() {  
    2.     var url = $("#basePath").val() + "user/check.jpg?number="+Math.random();  
    3.     $("#img").attr("src",url);  
    4. }  


    验证:

    获取session中的code与前台传回的code是否一致

    [java] view plain copy
     
     print?
    1. /** 
    2.      * 验证码验证 
    3.      *  
    4.      * @param session 
    5.      * @param code 
    6.      */  
    7.     private void checkCode(HttpSession session, String code) {  
    8.         String codeSession = (String) session.getAttribute(“code”);  
    9.         if (StringUtils.isEmpty(codeSession)) {  
    10.             log.error("没有生成验证码信息");  
    11.             throw new IllegalStateException("ERR-01000");  
    12.         }  
    13.         if (StringUtils.isEmpty(code)) {  
    14.             log.error("未填写验证码信息");  
    15.             throw new BussinessException("ERR-06018");  
    16.         }  
    17.         if (codeSession.equalsIgnoreCase(code)) {  
    18.             // 验证码通过  
    19.         } else {  
    20.             log.error("验证码错误");  
    21.             throw new BussinessException("ERR-06019");  
    22.         }  
    23.     }  



    工具类:

    [java] view plain copy
     
     print?
    1. import java.awt.Color;  
    2. import java.awt.Font;  
    3. import java.awt.Graphics;  
    4. import java.awt.image.BufferedImage;  
    5. import java.util.Random;  
    6. /** 
    7.  * 验证码生成工具 
    8.  * @author HXL 
    9.  * 
    10.  */  
    11. public class CaptchaUtil {  
    12.     private BufferedImage image;// 图像  
    13.     private String str;// 验证码  
    14.     private static char code[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789".toCharArray();  
    15.   
    16.     public static final String SESSION_CODE_NAME="code";  
    17.       
    18.     private CaptchaUtil() {  
    19.         init();// 初始化属性  
    20.     }  
    21.   
    22.     /* 
    23.      * 取得RandomNumUtil实例 
    24.      */  
    25.     public static CaptchaUtil Instance() {  
    26.         return new CaptchaUtil();  
    27.     }  
    28.   
    29.     /* 
    30.      * 取得验证码图片 
    31.      */  
    32.     public BufferedImage getImage() {  
    33.         return this.image;  
    34.     }  
    35.   
    36.     /* 
    37.      * 取得图片的验证码 
    38.      */  
    39.     public String getString() {  
    40.         return this.str;  
    41.     }  
    42.   
    43.     private void init() {  
    44.         // 在内存中创建图象  
    45.         int width = 85, height = 20;  
    46.         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
    47.         // 获取图形上下文  
    48.         Graphics g = image.getGraphics();  
    49.         // 生成随机类  
    50.         Random random = new Random();  
    51.         // 设定背景色  
    52.         g.setColor(getRandColor(200, 250));  
    53.         g.fillRect(0, 0, width, height);  
    54.         // 设定字体  
    55.         g.setFont(new Font("Times New Roman", Font.PLAIN, 18));  
    56.         // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到  
    57.         g.setColor(getRandColor(160, 200));  
    58.         for (int i = 0; i < 155; i++) {  
    59.             int x = random.nextInt(width);  
    60.             int y = random.nextInt(height);  
    61.             int xl = random.nextInt(12);  
    62.             int yl = random.nextInt(12);  
    63.             g.drawLine(x, y, x + xl, y + yl);  
    64.         }  
    65.         // 取随机产生的认证码(4位数字)  
    66.         String sRand = "";  
    67.         for (int i = 0; i < 4; i++) {  
    68.             String rand = String.valueOf(code[random.nextInt(code.length)]);  
    69.             sRand += rand;  
    70.             // 将认证码显示到图象中  
    71.             g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));  
    72.             // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成  
    73.             g.drawString(rand, 13 * i + 6, 16);  
    74.         }  
    75.         // 赋值验证码  
    76.         this.str = sRand;  
    77.   
    78.         // 图象生效  
    79.         g.dispose();  
    80.         // ByteArrayInputStream input = null;  
    81.         // ByteArrayOutputStream output = new ByteArrayOutputStream();  
    82.         // try {  
    83.         // ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);  
    84.         // ImageIO.write(image, "JPEG", imageOut);  
    85.         // imageOut.close();  
    86.         // input = new ByteArrayInputStream(output.toByteArray());  
    87.         // } catch (Exception e) {  
    88.         // System.out.println("验证码图片产生出现错误:" + e.toString());  
    89.         // }  
    90.         // this.image = input  
    91.         this.image = image;/* 赋值图像 */  
    92.     }  
    93.   
    94.     /* 
    95.      * 给定范围获得随机颜色 
    96.      */  
    97.     private Color getRandColor(int fc, int bc) {  
    98.         Random random = new Random();  
    99.         if (fc > 255)  
    100.             fc = 255;  
    101.         if (bc > 255)  
    102.             bc = 255;  
    103.         int r = fc + random.nextInt(bc - fc);  
    104.         int g = fc + random.nextInt(bc - fc);  
    105.         int b = fc + random.nextInt(bc - fc);  
    106.         return new Color(r, g, b);  
    107.     }  
    108. }   

    最后展示:

  • 相关阅读:
    世界城堡论坛
    瑞典皇家理工学院工程实例:An Advanced Speech Codec for a Voice over IP Transmission System
    压缩域丢包补偿:Demo of Compressed Domain Packet Loss Concealment of Sinusoidally Coded Speech
    音频编解码器五大模块之:T
    瑞典皇家理工学院工程实例:Acoustic measurement system
    VOIP Codec 三剑客之 ISAC/ILBC ISAC (5) LPC Parameter Encode 模块
    通信语音音质评估:
    Frank Klemm's Musepack Page
    瑞典皇家理工学院工程实例:Sound localization
    Frank Klemm's Dither and Noise Shaping Page: Dither and Noise Shaping In MPC/MP+
  • 原文地址:https://www.cnblogs.com/yhtboke/p/6349490.html
Copyright © 2011-2022 走看看