基於SSH2框架下的 使用者註冊 驗證碼功能
阿新 • • 發佈:2019-02-14
jsp頁面:
<tr> <th width="320" >驗證碼:</th> <td width="741" > <s:textfield key="registerInfoBean.checkNumber" cssClass="inputtext" data-rule-required="true" /> <img id="chkNumber" src="registerChkNumber.action" /> </td> </tr>
js:
//驗證碼
$("#chkNumber").click(function(){
var timenow = new Date().getTime();
$(this).attr("src", "registerChkNumber.action?d="+timenow);
});
struts.xml檔案配置;<action name="registerChkNumber" class="registerAction" method="getChkNumber"> <result type="stream"> <param name="contentType">image/jpeg</param> <param name="inputtName">inputStream</param> </result> </action>
Action處理:
//輸出流
private ByteArrayInputStream inputStream;
/**
* 驗證碼獲取
*
*/
public String getChkNumber(){
this.setInputStream(this.registerService.getChkNumber());
return SUCCESS;
}
Service實現類方法:
/** * 獲取驗證碼 */ public ByteArrayInputStream getChkNumber(){ int width = 85, height = 25; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); Random random = new Random(); g.setColor(getRandColor(200, 255)); g.fillRect(0, 0, width, height); g.setFont(new Font("Times New Roman", Font.PLAIN, 18)); g.setColor(getRandColor(160, 200)); for(int i = 0; i < 155; i++) { int x1 = random.nextInt(width); int y1 = random.nextInt(height); int x2 = random.nextInt(12); int y2 = random.nextInt(12); g.drawLine(x1, y1, x2, y2); } String sRand = ""; for(int i = 0; i < 6; i++) { String rand = getRandomChar(); sRand += rand; g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110))); g.drawString(rand, 13*i+6, 16); } //存進session,用於驗證 ActionContext.getContext().getSession().put("randomImg", sRand.toLowerCase()); g.dispose(); ByteArrayOutputStream output = new ByteArrayOutputStream(); ImageOutputStream imageOut; try { imageOut = ImageIO.createImageOutputStream(output); ImageIO.write(image, "JPEG", imageOut); imageOut.close(); } catch (IOException e) { e.printStackTrace(); } ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray()); return input; } //顏色 public Color getRandColor(int fc, int bc){ Random random = new Random(); if(fc > 255) fc = 255; if(bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } //產生隨機數 public String getRandomChar(){ int rand = (int)Math.round(Math.random() * 2); long itmp = 0; char ctmp = '\u0000'; switch (rand) { case 1: itmp = Math.round(Math.random() * 25 + 65); ctmp = (char)itmp; return String.valueOf(ctmp); case 2: itmp = Math.round(Math.random() * 25 + 97); ctmp = (char)itmp; return String.valueOf(ctmp); default : itmp = Math.round(Math.random() * 9); } return String.valueOf(itmp); }
驗證提交驗證碼是否正確
//判斷驗證碼是否正確
if(registerInfo.getCheckNumber().toLowerCase().equals(
ActionContext.getContext().getSession().get("randomImg"))){
// 正確後的業務處理程式碼
}