34、驗證碼
學習目標:
1、瞭解驗證碼的作用
2、掌握驗證碼的實現
學習過程:
一、為什麼需要驗證碼
1、什麼是驗證碼
相信大家經常上網都會見到驗證碼的,如下圖:
你可以隨便開啟一個有驗證碼的網站看看,那到底什麼是驗證碼呢?驗證碼上面的數字或者字母是隨機生成的,驗證其實就是一副動態生成的圖片。使用者需要輸入和驗證碼生成的圖片內容一致的內容才可能繼續操作。
2、驗證碼有什麼作用呢
事實上驗證碼對使用者體驗非常不好,那為什麼很多網站還是需要使用驗證碼呢?其實驗證碼的真正作用是為了保護伺服器的,因為本身http協議可以允許使用者不斷訪問網站的,對一些安全性比較好或者需要修改資料庫內容的功能,使用者是可以很輕鬆就可以對其攻擊了,比如登入功能,如果不使用驗證碼,那麼很有可能有一些黑客對其進行密碼的暴力破解,如果是註冊等操作有可能會有人通過程式批量的新增資料,這樣你的資料庫很快就會蹦貴。驗證碼就是解決這些複雜問題的最簡單方式,目前還沒有比驗證碼更好的解決方式,所有很多網站還是會使用驗證碼。比如下面這段程式碼就可以批量的註冊使用者了。
public static void main(String[] args) { for (int i = 0; i < 100000; i++) { String weburl = "http://localhost:8080/userdem/admin/userServlet?op=add&username=liubao&sex=1"; try { URL url = new URL(weburl); URLConnection connection = url.openConnection(); BufferedReader br = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line = br.readLine(); while (line != null) { System.out.println(line); line = br.readLine(); } br.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
二、實現驗證
1、生成驗證碼
那麼我們如何可以實現驗證碼?事實驗證碼非常簡單,就是在伺服器中隨機生成四個字母或者數字,儲存在session中,並生成一副圖片,發給瀏覽器顯示即可。
(1)新建一個servlet,用於生成驗證碼圖片,同時把驗證碼字串儲存在session中。
public class ValidateServlet extends HttpServlet { // 驗證嗎圖片的寬度 private int width = 200;; // 高度 private int height = 80; // 驗證嗎的字元個數 private int codeCount = 4; private int x = 0; // 字型高度 private int fontHeight; private int codeY; 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' }; @Override public void init() throws ServletException { super.init(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 建立一個隨機數生成器類 Random random = new Random(); // 1、生成一幅圖片。 x = width / (codeCount + 1); fontHeight = height - 2; codeY = height - 4; // 定義影象buffer BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = buffImg.createGraphics(); // 將影象填充為白色 g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); // 建立字型,字型的大小應該根據圖片的高度來定。 Font font = new Font("Fixedsys", Font.PLAIN, fontHeight); // 設定字型。 g.setFont(font); // 畫邊框。 g.setColor(Color.BLACK); g.drawRect(0, 0, width - 1, height - 1); // 隨機產生160條幹擾線,使圖象中的認證碼不易被其它程式探測到。 g.setColor(Color.BLACK); for (int i = 0; i < 160; i++) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x, y, x + xl, y + yl); } // 2、生產隨機數 // randomCode用於儲存隨機產生的驗證碼,以便使用者登入後進行驗證。 StringBuffer randomCode = new StringBuffer(); int red = 0, green = 0, blue = 0; // 隨機產生codeCount數字的驗證碼。 for (int i = 0; i < codeCount; i++) { // 得到隨機產生的驗證碼數字。 String strRand = String.valueOf(codeSequence[random.nextInt(36)]); // 產生隨機的顏色分量來構造顏色值,這樣輸出的每位數字的顏色值都將不同。 red = random.nextInt(255); green = random.nextInt(255); blue = random.nextInt(255); // 用隨機產生的顏色將驗證碼繪製到影象中。 g.setColor(new Color(red, green, blue)); g.drawString(strRand, (i + 1) * x-30, codeY); // 將產生的四個隨機數組合在一起。 randomCode.append(strRand); } // 3、要把隨機數放在session中 // 將四位數字的驗證碼儲存到Session中。 HttpSession session = request.getSession(); session.setAttribute("validateCode", randomCode.toString()); // 4、輸出圖片 // 禁止影象快取。 response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); // 將影象輸出到Servlet輸出流中。 ServletOutputStream out = response.getOutputStream(); ImageIO.write(buffImg, "jpeg", out); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
(2)servlet在web.xml的配置如下:
<servlet>
<servlet-name>ValidateServlet</servlet-name>
<servlet-class>com.servlet.ValidateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ValidateServlet</servlet-name>
<url-pattern>/validateServlet</url-pattern>
</servlet-mapping>
(3)在登入頁面中使用,就是使用img控制元件,src指向這個servlet路徑就可以了
<form action="loginServlert" method="post">
使用者名稱:<input name="username" value="liubao" /> <br /> 密碼:<input name="pass" value="123"
type="password" /> <br />
驗證碼:<input name="vcode"/> <img alt="" id="imgcode" src="validateServlet" onclick="updatecode()" style="cursor: pointer;" >
<br />
<input type="submit" value="登入" />
</form>
2、驗證碼的驗證功能
使用者輸入的驗證碼和儲存session驗證比較,如果相同,才進行資料庫的操作,我們應該在登入判斷之前完成
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session=request.getSession();
//先判斷使用者輸入的驗證碼是否正確
String sessionCode=session.getAttribute("validateCode").toString();
String userCode=request.getParameter("vcode");
System.out.println(sessionCode+":"+userCode);
if(!sessionCode.equalsIgnoreCase(userCode)){
//session.setAttribute("error", "驗證碼錯誤");
response.sendRedirect("index.jsp?error=cerror");
return;
}
UserDao userDao=new UserDao();
String username=request.getParameter("username");
String pass=request.getParameter("pass");
User user=userDao.login(username, pass);
if(user!=null){
//session.removeAttribute("error");
request.getSession().setAttribute("user", user);
response.sendRedirect("admin/userServlet?op=list");
}else{
//session.setAttribute("error", "使用者名稱密碼錯誤");
response.sendRedirect("index.jsp?error=uerror");
}
}
三、優化介面顯示
這樣我們的驗證碼就實現了,下面我們在優化一下介面,使用者如果看不清驗證還可以換一張試一試的,這個功能使用js就可以完成了。
<script type="text/javascript">
function updatecode(){
var imgcode=document.getElementById("imgcode");
imgcode.src="validateServlet?abc="+new Date();
}
</script>