springMVC+Java驗證碼完善注冊功能

eg756 9年前發布 | 58K 次閱讀 SpringMVC Spring MVC Web框架

這篇文章簡單的寫了一個java驗證碼,為之前寫過的springMVC注冊功能加上驗證碼,驗證碼的作用就不多說了,防止機器人程序惡意注冊什么的。。。

基本的注冊功能的實現請查看之前的文章Maven搭建springMVC+spring+hibernate實現用戶注冊

其中,我修改了該注冊程序的部分代碼,其中User.java,加上了password和code的屬性,同時將password持久到數據庫,code屬性使用@transient注解使其不被持久到數據庫。

User.java 中加上這兩個屬性,至于User的構造方法修改為public User(String id, Date regtime, String username,String password) 就不貼代碼了。

private String password;
    @Column(name="password",nullable=false,length=20)
    public String getPassword() {
        return password;
    }

public void setPassword(String password) {
    this.password = password;
}
private String code;
@Transient   //不需要持久到DB的屬性使用該注解
public String getCode() {
    return code;
}

public void setCode(String code) {
    this.code = code;
}</pre> <p><span style="font-size:14px;">下面是驗證碼生成的controller,大部分代碼都寫上了注釋。</span> </p>

CodeController.java

package com.sgl.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.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;

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

@Controller public class CodeController { private int width = 90;//定義圖片的width private int height = 20;//定義圖片的height private int codeCount = 4;//定義圖片上顯示驗證碼的個數 private int xx = 15; private int fontHeight = 18; private int codeY = 16; char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

@RequestMapping("/code")
public void getCode(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {

    // 定義圖像buffer
    BufferedImage buffImg = new BufferedImage(width, height,
            BufferedImage.TYPE_INT_RGB);

// Graphics2D gd = buffImg.createGraphics(); //Graphics2D gd = (Graphics2D) buffImg.getGraphics(); Graphics gd = buffImg.getGraphics(); // 創建一個隨機數生成器類 Random random = new Random(); // 將圖像填充為白色 gd.setColor(Color.WHITE); gd.fillRect(0, 0, width, height);

    // 創建字體,字體的大小應該根據圖片的高度來定。
    Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
    // 設置字體。
    gd.setFont(font);

    // 畫邊框。
    gd.setColor(Color.BLACK);
    gd.drawRect(0, 0, width - 1, height - 1);

    // 隨機產生40條干擾線,使圖象中的認證碼不易被其它程序探測到。
    gd.setColor(Color.BLACK);
    for (int i = 0; i < 40; i++) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(12);
        int yl = random.nextInt(12);
        gd.drawLine(x, y, x + xl, y + yl);
    }

    // randomCode用于保存隨機產生的驗證碼,以便用戶登錄后進行驗證。
    StringBuffer randomCode = new StringBuffer();
    int red = 0, green = 0, blue = 0;

    // 隨機產生codeCount數字的驗證碼。
    for (int i = 0; i < codeCount; i++) {
        // 得到隨機產生的驗證碼數字。
        String code = String.valueOf(codeSequence[random.nextInt(36)]);
        // 產生隨機的顏色分量來構造顏色值,這樣輸出的每位數字的顏色值都將不同。
        red = random.nextInt(255);
        green = random.nextInt(255);
        blue = random.nextInt(255);

        // 用隨機產生的顏色將驗證碼繪制到圖像中。
        gd.setColor(new Color(red, green, blue));
        gd.drawString(code, (i + 1) * xx, codeY);

        // 將產生的四個隨機數組合在一起。
        randomCode.append(code);
    }
    // 將四位數字的驗證碼保存到Session中。
    HttpSession session = req.getSession();
    System.out.print(randomCode);
    session.setAttribute("code", randomCode.toString());

    // 禁止圖像緩存。
    resp.setHeader("Pragma", "no-cache");
    resp.setHeader("Cache-Control", "no-cache");
    resp.setDateHeader("Expires", 0);

    resp.setContentType("image/jpeg");

    // 將圖像輸出到Servlet輸出流中。
    ServletOutputStream sos = resp.getOutputStream();
    ImageIO.write(buffImg, "jpeg", sos);
    sos.close();
}

}</pre>

改寫UserController.java中的注冊代碼

將UserController.java中add方法修改為下面這樣。

@RequestMapping("/user")
    public ModelAndView addUser(User user,HttpSession session) {
        ModelAndView mav=new ModelAndView();
        if (!(user.getCode().equalsIgnoreCase(session.getAttribute("code").toString()))) {  //忽略驗證碼大小寫
            mav.setViewName("error");
            mav.addObject("msg","驗證碼不正確");
            return mav;
        }else {
            user.setId(UUID.randomUUID().toString());
            user.setRegtime(new Date());
            try {
                userService.addUser(user);
            //  request.setAttribute("user", user);
                mav.setViewName("success");
                mav.addObject("user", user);
                mav.addObject("msg", "注冊成功了,可以去登陸了");
                return mav;
            } catch (Exception e) {
                mav.setViewName("menu");
                mav.addObject("user", null);
                mav.addObject("msg", "注冊失敗");
                return mav;
            }
        }
    }

然后就是修改前臺頁面了

將注冊的index.jsp的form修改

 

<form action="user.html" method="post">
 <table width="207" border="0" align="center">
        <tr>
          <td colspan="2" align="center" nowrap="nowrap">用戶注冊</td>
        </tr>
        <tr>
          <td width="68" nowrap="nowrap">用戶名</td>
          <td width="127" nowrap="nowrap"><label>
            <input name="username" type="text" id="username" size="20" />
          </label></td>
        </tr>
        <tr>
          <td nowrap="nowrap">密    碼</td>
          <td nowrap="nowrap"><input name="password" type="password" id="password" size="20" maxlength="10" /></td>
        </tr>
        <tr><td>驗證碼</td><td><input id="index_code" name="code" type="text" /></td>
       <td> <img id="imgObj" alt="驗證碼" src="code.html" />
        <a href="#" onclick="changeImg()">換一張</a></td></tr>
        <tr>
          <td colspan="2" align="center" nowrap="nowrap"><label>
            <input type="submit"  value="注冊" />
            <input type="reset"  value="重填" />
          </label></td>
        </tr>
  </table>
</form>

注意<img />標簽的src的寫法,寫成code.html。

其中用于實現“換一張”功能的javascript為下

<script type="text/javascript">
    function changeImg() {
        var imgSrc = $("#imgObj");
        var src = imgSrc.attr("src");
        imgSrc.attr("src", chgUrl(src));
    }
    //時間戳   
    //為了使每次生成圖片不一致,即不讓瀏覽器讀緩存,所以需要加上時間戳   
    function chgUrl(url) {
        var timestamp = (new Date()).valueOf();
        url = url.substring(0, 17);
        if ((url.indexOf("&") >= 0)) {
            url = url + "×tamp=" + timestamp;
        } else {
            url = url + "?timestamp=" + timestamp;
        }
        return url;
    }
</script>

其中,這一段js用到了jquery,別忘了在head中把jquery的js給引進來。

<script type="text/javascript" src="js/jquery-easyui-1.3.1/jquery-1.8.0.min.js"></script>

到此為止,一個完整的注冊程序就完成了。部署,測試,如圖

springMVC+Java驗證碼完善注冊功能

注冊成功了如下

springMVC+Java驗證碼完善注冊功能

驗證碼輸入錯誤,如下

springMVC+Java驗證碼完善注冊功能

然后就error了。。springMVC+Java驗證碼完善注冊功能

springMVC+Java驗證碼完善注冊功能

這個注冊的功能就基本完善了,當然,其實error的提示應該在原來的注冊頁面,可以使用ajax來實現,我只是寫示例程序,就沒那樣做了。追求完美的可以自己重構一下Controller的代碼,返回json給瀏覽器,再用ajax實現不刷新頁面,就可以實現真正的注冊功能了。
最后再啰嗦一句,需要這個demo項目源代碼的孩子,請聯系郵箱sgl-2014@qq.com

或者去CSDN Code上去下載,地址:https://code.csdn.net/Sgl731524380/verificationcode/tree/master

原文地址:http://blog.csdn.net/javasgl/article/details/8939147

 本文由用戶 eg756 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!