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

來源:互聯網
上載者:User

標籤:

這篇文章簡單的寫了一個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;}

下面是驗證碼產生的controller,大部分代碼都寫上了注釋。

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;@Controllerpublic class CodeController {private int width = 90;//定義圖片的widthprivate int height = 20;//定義圖片的heightprivate 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 {// 定義映像bufferBufferedImage 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();}}

改寫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>

到此為止,一個完整的註冊程式就完成了。部署,測試,

註冊成功了如下

驗證碼輸入錯誤,如下

然後就error了。。

這個註冊的功能就基本完善了,當然,其實error的提示應該在原來的註冊頁面,可以使用ajax來實現,我只是寫樣本程式,就沒那樣做了。追求完美的可以自己重構一下Controller的代碼,返回json給瀏覽器,再用ajax實現不重新整理頁面,就可以實現真正的註冊功能了。
最後再囉嗦一句,需要這個demo項目原始碼的孩子,請聯絡郵箱[email protected]

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

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.