SSM实现验证码校验

SSM实现验证码校验

木来 木来

首先,验证码校验的流程就是:当页面加载时,会向后台请求一次验证码。

然后,java会随机生成几个字母,然后通过画笔工具画出验证码来,将验证码放到session中,然后将其图片返回到前端,前端接收并展示。校验时,将用户输入的验证码与session中存放的验证码进行对比,判断验证码是否输入正确。

1.我的验证码Controller

package weike.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import weike.bean.message;


/**
 * 
* <p>Title:AuthCodeController </p>
* <p>Description: 验证码的控制类</p>
* <p>Company:www.inx.fun</p>
* @author  时玉龙
* @date    2017年6月18日下午6:13:52
 */
@Controller
@RequestMapping("/authcode")
public class AuthCodeController {

    
    
    
    
        public static final int AUTHCODE_LENGTH = 5;   // 验证码的长度
        public static final int SINGLECODE_WIDTH = 15; // 单个验证码的宽度
        public static final int SINGLECODE_HEIGHT = 30; // 单个验证码的高度
        public static final int SINGLECODE_GAP = 4; // 单个验证码之间的间隙
        public static final int IMG_WIDTH = AUTHCODE_LENGTH * (SINGLECODE_WIDTH + SINGLECODE_GAP);  
        public static final int IMG_HEIGHT = SINGLECODE_HEIGHT;  
        public static final char[] CHARS = {'1', '2', '3', '4', '5', '6','8',  
            '9','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H','K','M',  
            'N','P', 'Q', 'R', 'S','U', 'V', 'W', 'X', 'Y', 'Z' };  
        static Random random = new Random();
        
        
        public static String getAuthCode() {  
            StringBuffer buffer = new StringBuffer();  
            for (int i = 0; i < 5; i++) {
                buffer.append(CHARS[random.nextInt(CHARS.length)]);  
            }  
            return buffer.toString();  
        }  
        
    
    
        
        
        
        public static BufferedImage getAuthImg(String authCode) {  
             //设置图片的高、宽、类型  
            //RGB编码:red、green、blue  
            BufferedImage img = new BufferedImage(IMG_WIDTH, IMG_HEIGHT,  
                    BufferedImage.TYPE_INT_BGR);  
            //得到图片上的一个画笔  
            Graphics g = img.getGraphics();  
            //设置画笔的颜色,用来做背景色  
            g.setColor(Color.getColor("#f3f4f6"));  
            //用画笔来填充一个矩形,矩形的左上角坐标,宽,高  
            g.fillRect(0, 0, IMG_WIDTH, IMG_HEIGHT);  
            //将画笔颜色设置为黑色,用来写字  
            g.setColor(Color.RED);  
            //设置字体:宋体、不带格式的、字号  
            g.setFont(new Font("宋体", Font.PLAIN, SINGLECODE_HEIGHT + 5));  
            //输出数字  
            char c;  
            for (int i = 0; i < authCode.toCharArray().length; i++) {  
            //取到对应位置的字符  
                c = authCode.charAt(i);  
            //画出一个字符串:要画的内容,开始的位置,高度  
                g.drawString(c + "", i * (SINGLECODE_WIDTH + SINGLECODE_GAP)  
                        + SINGLECODE_GAP / 2, IMG_HEIGHT);  
            }  
            Random random = new Random();  
           
            return img;  
        }  
        
        
        
        
        @RequestMapping("/AuthCodeValidated")
        public void AuthCodeValidated(HttpServletRequest request,HttpServletResponse response) throws Exception{
              String authCode = AuthCodeController.getAuthCode();    
              //将验证码保存到session中,便于以后验证 
              request.getSession().setAttribute("authCode", authCode);
              try {    
                  //发送图片  
                  ImageIO.write(AuthCodeController.getAuthImg(authCode), "JPG", response.getOutputStream());    
              } catch (IOException e){    
                  e.printStackTrace();    
              }    
        }
        
        //进行注册的验证码校验
        @RequestMapping("/RegistertoAuthCodeValidated")
              public @ResponseBody int RegistertoAuthCodeValidated(@RequestBody message msg,HttpServletRequest request) throws Exception{
                  int num=0;
                    //将验证码保存到session中,便于以后验证 
            String authcode=(String)request.getSession().getAttribute("authCode");
            
            
            if(authcode.equals(msg.getAuthcode())){
                num=1;
            }
            
                 
                return num;  
              }
    
}

2.我将验证码放入注册页面了,这是我注册页面的from表单

 <form id="register-form" name="register_form" class="form-vertical" method="post" action="${pageContext.request.contextPath }/user/findUserExist" novalidate="novalidate" data-widget-cid="widget-0">
                             <div class="form-group mb40">
                <label class="control-label required" for="register_emailOrMobile">常用邮箱</label>
                <div class="controls">
                    <label class="fa-label">
                      <i class="iconfont icon-icon-yxj-pencil"></i>
                    </label>
                    <input type="text" id="register_emailOrMobile" name="emailOrMobile" required="required" class="form-control"  placeholder="常用邮箱" data-widget-cid="widget-2" data-explain="">
                    <p class="help-block">

                    </p>
                </div>
            </div>
        
        <div class="form-group mb40">
            <label class="control-label required" for="register_nickname">昵称</label>
            <div class="controls">
                <label class="fa-label">
                    <i class="iconfont icon-yonghu"></i>
                </label>
                <input type="text" id="register_nickname" name="nickname" required="required" class="form-control"  placeholder="请输入昵称(注册后不能再修改)" data-widget-cid="widget-3" data-explain="">
            <div class="help-block" style="display:none;"></div></div>
        </div>
        
        <div class="form-group mb40">
            <label class="control-label required" for="register_password">密码</label>
            <div class="controls">
               <label class="fa-label">
                    <i class="iconfont icon-mima"></i>
                  </label>
                <input type="password" id="register_password" name="password" required="required" class="form-control" placeholder="密码" data-widget-cid="widget-4" data-explain="">
            <div class="help-block" style="display:none;"></div></div>
        </div>

                    <div class="form-group mb40 captcha_div">
                <label class="control-label required" for="captcha_num">验证码</label>
                <div class="controls row">
                    <div class="col-xs-6">
                        <input type="text" class="form-control ident" id="captcha_num" name="captcha_num" maxlength="5" placeholder="验证码" required="required"  data-widget-cid="widget-1" data-explain="">
                    </div>
                    <div class="col-xs-6 ident-img">
                        <img src="./authcode/AuthCodeValidated.action"  id="getcode" name="SafeCodeImg" title="看不清,点击换一张" style="cursor:pointer;" alt="看不清,点击换一张" onclick="this.src=&quot;<%=basePath%>authcode/AuthCodeValidated.action?&amp;&quot;+Math.random()">
                    </div>
                <div class="help-block" style="display:none;"></div></div>
            </div>
        
                    <div class="form-group mb40 hidden email_mobile_msg">
                <label class="control-label required" for="sms_code">短信验证码</label>
                <div class="controls row">
                    <div class="col-xs-6">
                        <input type="text" class="form-control ident" id="sms_code" name="sms_code" placeholder="短信验证码" required="required" >
                    </div>
                    <div class="col-xs-6">
                        <a href="javascript:;" data-toggle="modal" class="btn ident btn-primary btn-lg  form-control  js-sms-send disabled"  >
                            <span id="js-time-left"></span>
                            <span id="js-fetch-btn-text">获取短信验证码</span>
                        </a>
                    </div>
                </div>
            </div>
                            <div class="form-group mb40 agren">
                <div class="controls">
                    <label><input type="checkbox" id="user_terms" checked="checked" data-widget-cid="widget-5" data-explain=""> 我已阅读并同意<a href="./WebContent/page/public/agreement.html" target="_blank">《服务协议》</a>
                    </label>
                <div class="help-block" style="display:none;"></div></div>
            </div>
                <div class="form-group">
          <div class="controls">
            <button type="submit" id="register-btn "  class="login-btn btn-primary btn zhuceanniu">注册
            </button>
          </div>
        </div>

       
      
</form>

在其中,是通过这一句代码来请求验证码图片:

   <img src="./authcode/AuthCodeValidated.action"  id="getcode" name="SafeCodeImg" title="看不清,点击换一张" style="cursor:pointer;" alt="看不清,点击换一张" onclick="this.src=&quot;<%=basePath%>authcode/AuthCodeValidated.action?&amp;&quot;+Math.random()">

在请求后面会加一个随机数,这样的好处就是每次请求,浏览器都会认为是不同的请求,如果你不加任何参数,浏览器会认为每次请求都是同一次请求,所以将不会真正的去请求后台验证码。

所以说,浏览器很懒~~~

0 条评论