java web驗證碼實現代碼分享_java

來源:互聯網
上載者:User

驗證碼的作用:通常的登入或者註冊系統時,都會要求使用者輸入驗證碼,以此區別使用者行為和電腦程式行為,目的是有人防止惡意註冊、暴力破解密碼等。

實現驗證碼的思路:用 server 實現隨機產生數字和字母組成圖片的功能,用 jsp 頁面實現顯示驗證碼和使用者輸入驗證碼的功能,再用 server 類分別擷取圖片和使用者輸入的資料,判斷兩個資料是否一致。 
代碼實現 

1.編寫數字、英文隨機產生的 server 類,源碼:

package com;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.PrintWriter;import javax.imageio.ImageIO;import javax.servlet.ServletException;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;public class logcheck extends HttpServlet { public logcheck() {  super(); }  public void destroy() {  super.destroy();  } public void doGet(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {  doPost(request, response); } /*實現的核心代碼*/ public void doPost(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {  response.setContentType("image/jpeg");  HttpSession session=request.getSession();  int width=60;  int height=20;    //設定瀏覽器不要緩衝此圖片  response.setHeader("Pragma", "No-cache");  response.setHeader("Cache-Control", "no-cache");  response.setDateHeader("Expires", 0);    //建立記憶體配置圖像並獲得圖形上下文  BufferedImage image=new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);  Graphics g=image.getGraphics();    /*   * 產生隨機驗證碼   * 定義驗證碼的字元表   */  String chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";  char[] rands=new char[4];  for(int i=0;i<4;i++){   int rand=(int) (Math.random() *36);   rands[i]=chars.charAt(rand);  }    /*   * 產生映像   * 畫背景   */  g.setColor(new Color(0xDCDCDC));  g.fillRect(0, 0, width, height);    /*   * 隨機產生120個幹擾點   */    for(int i=0;i<120;i++){   int x=(int)(Math.random()*width);   int y=(int)(Math.random()*height);   int red=(int)(Math.random()*255);   int green=(int)(Math.random()*255);   int blue=(int)(Math.random()*255);   g.setColor(new Color(red,green,blue));   g.drawOval(x, y, 1, 0);  }  g.setColor(Color.BLACK);  g.setFont(new Font(null, Font.ITALIC|Font.BOLD,18));    //在不同高度輸出驗證碼的不同字元  g.drawString(""+rands[0], 1, 17);  g.drawString(""+rands[1], 16, 15);  g.drawString(""+rands[2], 31, 18);  g.drawString(""+rands[3], 46, 16);  g.dispose();    //將映像傳到用戶端  ServletOutputStream sos=response.getOutputStream();  ByteArrayOutputStream baos=new ByteArrayOutputStream();  ImageIO.write(image, "JPEG", baos);  byte[] buffer=baos.toByteArray();  response.setContentLength(buffer.length);  sos.write(buffer);  baos.close();  sos.close();    session.setAttribute("checkcode", new String(rands)); }  public void init() throws ServletException {  // Put your code here }}

2.用於顯示驗證碼的頁面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head>  <base href="<%=basePath%>">    <title>index</title>  <meta http-equiv="pragma" content="no-cache">  <meta http-equiv="cache-control" content="no-cache">  <meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  <meta http-equiv="description" content="This is my page">  <!--  <link rel="stylesheet" type="text/css" href="styles.css">  --> </head>  <body> <form action="yanzheng" method="post">   <input type="text" name="name" size="5" maxlength="4">  <a href="index.jsp"><img border="0" src="logcheck"></a><br><br>       <input type="submit" value="提交"> </form> </body></html>

3.用於檢驗輸入的驗證碼是否正確:

package com;import java.io.IOException;import java.io.PrintWriter;import javax.jms.Session;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;public class yanzheng extends HttpServlet { public yanzheng() {  super(); } public void destroy() {  super.destroy();  } public void doGet(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {  doPost(request, response); } /*核心代碼*/ public void doPost(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {  String info=null;  /*擷取輸入的值*/  String value1=request.getParameter("name");  /*擷取圖片的值*/  HttpSession session=request.getSession();  String value2=(String)session.getAttribute("checkcode");  /*對比兩個值(字母不區分大小寫)*/  if(value2.equalsIgnoreCase(value1)){   info="驗證碼輸入正確";  }else{   info="驗證碼輸入錯誤";  }  System.out.println(info);  request.setAttribute("info", info);  request.getRequestDispatcher("/login.jsp").forward(request, response); }  public void init() throws ServletException {  // Put your code here }}

4.顯示輸入結構介面(輸入驗證碼是否正確): 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>">  <title>My JSP 'login.jsp' starting page</title>  <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0">  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head>  <body> <%=request.getAttribute("info") %> </body></html>

5.項目結構、效果截圖:

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.