1. 程式人生 > >java登入驗證碼(框架版)

java登入驗證碼(框架版)

java後臺做的驗證碼圖片,算是比較方便的一種了,今天正好在新搭的框架裡寫了,使用的非常完美,哈哈大笑,話不多說,開始上程式碼

1.登入介面進入controller層

 //生成登入驗證碼
	 @RequestMapping("createCode")
	 public void createCode(HttpServletRequest request,HttpServletResponse response) throws IOException{
		 //通知瀏覽器不要快取
		 response.setHeader("Expires","-1");//控制快取的失效日期
		 response.setHeader("Cache-Control","no-cache");//必須先與伺服器確認返回的響應是否被更改,然後才能使用該響應來滿足後續對同一個網址的請求
		 response.setHeader("Pragma","-1");
		 CaptchaUtil util=CaptchaUtil.Instance();
		 // 將驗證碼輸入到session中,用來驗證  
		 String code=util.getString();
		 request.getSession().setAttribute("code",code);
		// 輸出到web頁面  
		 ImageIO.write(util.getImage(), "jpg", response.getOutputStream());
	 }
2.進入生成驗證碼的處理類

package com.lq.util;

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

/** 
 * 驗證碼生成工具 
 * @author df 
 * 
 */  
public class CaptchaUtil {
   private BufferedImage image;//影象
   private String str;//驗證碼
   private static char code[] ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789".toCharArray();
   public static final String SESSION_CODE_NAME="code";
   
   private CaptchaUtil(){
	   init();// 初始化屬性 
   }
   //取得RandomNumUtil例項 
   public static CaptchaUtil Instance(){
	   return new CaptchaUtil();
   }
   //取得驗證碼圖片 
   public BufferedImage getImage(){
	   return this.image;
   }
   //取得圖片的驗證碼  
   public String getString(){
	   return this.str;
   }
   
   private void init() {
	  // 在記憶體中建立圖象  
	 int width=85,height=20;
	 BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
	 // 獲取圖形上下文  
	 Graphics g =image.getGraphics();
	// 生成隨機類  
	 Random random=new Random();
	 //設定背景色
	 g.setColor(getRandColor(200,250));
	 g.fillRect(0, 0, width, height);
	 //設定字型
	 g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
	 // 隨機產生155條幹擾線,使圖象中的認證碼不易被其它程式探測到  
	 g.setColor(getRandColor(160,200));
	 for(int i=0;i<155;i++){
		 int x=random.nextInt(width);
		 int y=random.nextInt(height);
		 int x1=random.nextInt(12);
		 int y1=random.nextInt(12);
		 g.drawLine(x, y, x+x1, y+y1);
	 }
	 // 取隨機產生的認證碼(4位數字)  
	 String sRand="";
	 for(int i=0;i<4;i++){
		 String rand=String.valueOf(code[random.nextInt(code.length)]);
		 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);
	 }
	 this.str=sRand;
	 // 圖象生效 
	 g.dispose();
	 this.image=image;/* 賦值影象 */  
   }
   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);
   }
   
}

3.生成的影象和隨機字母傳到登入的頁面上

<span>驗證碼:</span>
				     <input type="code" id="code" name="code" class="login_input" />//輸入驗證碼的框,後期需要驗證
				     <img id="img" src="<%=basePath%>basextgl/createCode" onclick="refresh()"> //跳到Controller層createCode方法裡獲取隨機數和圖片

4點選加載出來的圖片開始切換驗證碼

  //點選改變驗證碼
  function refresh(){
	  //$("#basePath").val()+
	  var url="/Spring-MVC-model/basextgl/createCode?number="+Math.random();//這裡沒有隨機引數的話就只進兩次後臺就再也不進了,這個現在還不太明白為什麼
	  $("#img").attr("src",url);  
  }
現在為止驗證碼加載出來了,就差登入的時候驗證了
	<li class="login-sub">
					<input type="submit" name="button" value="登入" onclick="LoginDate();"/><span id="error" style="color: red"></span>
                    <%--<input type="reset" name="Reset" value="重置" /> --%>
				</li>
  function LoginDate(){
	  var code=$("#code").val();
	  $.ajax({
	    	url:"/Spring-MVC-model/login/cheklogin",
	    	type:"post",
	    	async:false,
	    	data:{code":code},
	    	success:function(data){
	    		if(data=="1"){
	    			alert("登入成功");
	    			//window.location.href="/Spring-MVC-model/basextgl/topMain"
	    			window.location.href="/Spring-MVC-model/basextgl/indexMethod"
	    		}else if(data=="2"){
	    			$("#error").text("驗證碼輸入錯誤,請重新填寫");
	    		}
	    	}
	    })
  }

4.最後一步進入後臺驗證我們輸入的驗證碼是否正確
@RequestMapping("/cheklogin")
	public void cheklogin(String username, String password,String code,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		PrintWriter out = response.getWriter();
		HttpSession session=request.getSession();
		//取出存在session的隨機數字
		String codeSession=(String)session.getAttribute("code");
		//StringUtils是JDK提供的String型別操作方法的補充,並且是null安全的(即如果輸入引數String為null則不會丟擲NullPointerException,而是做了相應處理
		/*if (StringUtils.isEmpty(codeSession)) {  
            log.error("沒有生成驗證碼資訊");  
            throw new IllegalStateException("ERR-01000");  
        }  
        if (StringUtils.isEmpty(code)) {  
            log.error("未填寫驗證碼資訊");  
            throw new BussinessException("ERR-06018");  
        }  */
		
		//檢查驗證碼
		String strCode="";
		if(codeSession.equalsIgnoreCase(code)){//忽略大小寫
		strCode="1";
		}else{
                strCode="2"
		}
		//驗證通過才成功
		if(strCode.equals("1")){
			out.print("1");
		}else{
			 out.print("2");
			
		}
	}

最後的樣子就是這樣的