一個完整的servlet+ajax驗證碼

來源:互聯網
上載者:User

產生圖片流的servlet

package com.jimo.tool;<br />import java.awt.Color;<br />import java.awt.Font;<br />import java.awt.Graphics2D;<br />import java.awt.image.BufferedImage;<br />import java.util.Random; </p><p>import javax.imageio.ImageIO;<br />import javax.servlet.ServletException;<br />import javax.servlet.ServletOutputStream;<br />import javax.servlet.http.HttpServlet;<br />import javax.servlet.http.HttpServletRequest;<br />import javax.servlet.http.HttpServletResponse;<br />import javax.servlet.http.HttpSession; </p><p>/**<br />* Package name : com.skcc.sample.action<br />* File name : VerifyCodeServlet.java<br />* Author : Administrator<br />* Date : 2008-9-4<br />* Description : VerifyCodeServlet<br />*/<br />public class VerifyCodeServlet extends HttpServlet { </p><p> /**<br /> * 驗證碼圖片的寬度。<br /> */<br /> private int width = 60; </p><p> /**<br /> * 驗證碼圖片的高度。<br /> */<br /> private int height = 20; </p><p> /**<br /> * 驗證碼字元個數<br /> */<br /> private int codeCount = 4; </p><p> /**<br /> * xx<br /> */<br /> private int xx = 0; </p><p> /**<br /> * 字型高度<br /> */<br /> private int fontHeight; </p><p> /**<br /> * codeY<br /> */<br /> private int codeY; </p><p> /**<br /> * codeSequence<br /> */<br /> char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',<br /> 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',<br /> 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; </p><p> /**<br /> * 初始化驗證圖片屬性<br /> */<br /> public void init() throws ServletException {<br /> // 從web.xml中擷取初始資訊<br /> // 寬度<br /> String strWidth = this.getInitParameter("width");<br /> // 高度<br /> String strHeight = this.getInitParameter("height");<br /> // 字元個數<br /> String strCodeCount = this.getInitParameter("codeCount"); </p><p> // 將配置的資訊轉換成數值<br /> try {<br /> if (strWidth != null && strWidth.length() != 0) {<br /> width = Integer.parseInt(strWidth);<br /> }<br /> if (strHeight != null && strHeight.length() != 0) {<br /> height = Integer.parseInt(strHeight);<br /> }<br /> if (strCodeCount != null && strCodeCount.length() != 0) {<br /> codeCount = Integer.parseInt(strCodeCount);<br /> }<br /> } catch (NumberFormatException e) {<br /> e.printStackTrace();<br /> } </p><p> xx = width / (codeCount + 1);<br /> fontHeight = height - 2;<br /> codeY = height - 4; </p><p> } </p><p> /**<br /> * @param req<br /> * @param resp<br /> * @throws ServletException<br /> * @throws java.io.IOException<br /> */<br /> protected void service(HttpServletRequest req, HttpServletResponse resp)<br /> throws ServletException, java.io.IOException { </p><p> // 定義映像buffer<br /> BufferedImage buffImg = new BufferedImage(width, height,<br /> BufferedImage.TYPE_INT_RGB);<br /> Graphics2D gd = buffImg.createGraphics(); </p><p> // 建立一個隨機數產生器類<br /> Random random = new Random(); </p><p> // 將映像填充為白色<br /> gd.setColor(Color.WHITE);<br /> gd.fillRect(0, 0, width, height); </p><p> // 建立字型,字型的大小應該根據圖片的高度來定。<br /> Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);<br /> // 設定字型。<br /> gd.setFont(font); </p><p> // 畫邊框。<br /> gd.setColor(Color.BLACK);<br /> gd.drawRect(0, 0, width - 1, height - 1); </p><p> // 隨機產生160條幹擾線,使圖象中的認證碼不易被其它程式探測到。<br /> gd.setColor(Color.BLACK);<br /> for (int i = 0; i < 1; i++) {<br /> int x = random.nextInt(width);<br /> int y = random.nextInt(height);<br /> int xl = random.nextInt(12);<br /> int yl = random.nextInt(12);<br /> gd.drawLine(x, y, x + xl, y + yl);<br /> } </p><p> // randomCode用於儲存隨機產生的驗證碼,以便使用者登入後進行驗證。<br /> StringBuffer randomCode = new StringBuffer();<br /> int red = 0, green = 0, blue = 0; </p><p> // 隨機產生codeCount數位驗證碼。<br /> for (int i = 0; i < codeCount; i++) {<br /> // 得到隨機產生的驗證碼數字。<br /> String strRand = String.valueOf(codeSequence[random.nextInt(36)]);<br /> // 產生隨機的顏色分量來構造顏色值,這樣輸出的每位元字的顏色值都將不同。<br /> red = random.nextInt(255);<br /> green = random.nextInt(255);<br /> blue = random.nextInt(255); </p><p> // 用隨機產生的顏色將驗證碼繪製到映像中。<br /> gd.setColor(new Color(red, green, blue));<br /> gd.drawString(strRand, (i + 1) * xx, codeY); </p><p> // 將產生的四個隨機數組合在一起。<br /> randomCode.append(strRand);<br /> }<br /> // 將四位元字的驗證碼儲存到Session中。<br /> HttpSession session = req.getSession();<br /> session.setAttribute("validateCode", randomCode.toString()); </p><p> // 禁止映像緩衝。<br /> resp.setHeader("Pragma", "no-cache");<br /> resp.setHeader("Cache-Control", "no-cache");<br /> resp.setDateHeader("Expires", 0); </p><p> resp.setContentType("image/jpeg"); </p><p> // 將映像輸出到Servlet輸出資料流中。<br /> ServletOutputStream sos = resp.getOutputStream();<br /> ImageIO.write(buffImg, "jpeg", sos);<br /> sos.close();<br /> }<br />}

 

處理結果的servlet

package com.jimo.tool;<br />import java.io.IOException;<br />import java.io.PrintWriter; </p><p>import javax.servlet.ServletException;<br />import javax.servlet.http.HttpServlet;<br />import javax.servlet.http.HttpServletRequest;<br />import javax.servlet.http.HttpServletResponse; </p><p>/**<br />* Package name : com.skcc.sample.action<br />* File name : ResultServlet.java<br />* Author : Administrator<br />* Date : 2008-9-4<br />* Description : ResultServlet<br />*/<br />public class ResultServlet extends HttpServlet { </p><p> /**<br /> * The doGet method of the servlet. <br><br /> *<br /> * This method is called when a form has its tag value method equals to get.<br /> *<br /> * @param request the request send by the client to the server<br /> * @param response the response send by the server to the client<br /> * @throws ServletException if an error occurred<br /> * @throws IOException if an error occurred<br /> */<br /> public void doGet(HttpServletRequest request, HttpServletResponse response)<br /> throws ServletException, IOException {<br /> doPost(request, response);<br /> } </p><p> /**<br /> * The doPost method of the servlet. <br><br /> *<br /> * This method is called when a form has its tag value method equals to post.<br /> *<br /> * @param request the request send by the client to the server<br /> * @param response the response send by the server to the client<br /> * @throws ServletException if an error occurred<br /> * @throws IOException if an error occurred<br /> */<br /> public void doPost(HttpServletRequest request, HttpServletResponse response)<br /> throws ServletException, IOException { </p><p> response.setContentType("text/html;charset=utf-8");<br /> String validateC = request.getSession().getAttribute("validateCode").toString();<br /> String veryCode = request.getParameter("c");<br /> PrintWriter out = response.getWriter();<br /> if(veryCode==null||"".equalsIgnoreCase(veryCode)){<br /> out.println("驗證碼為空白");<br /> }else{<br /> if(validateC.equalsIgnoreCase(veryCode)){<br /> out.println("驗證碼正確");<br /> }else{<br /> out.println("驗證碼錯誤");<br /> }<br /> }<br /> out.flush();<br /> out.close();<br /> }<br />}

 

頁面調用:

 <script language="javascript" type="text/javascript" src="js/checknum.js"></script>

 

<input id="veryCode" name="veryCode" type="text" />

<img id="imgObj" alt="" src="verifyCodeServlet" align="middle"/>

<input type="button" onclick="changeImg()" value="換一張" />

<div id="info" style="color:red; font-size:12px; font-weight:600">驗證碼為空白</div>

 

驗證的js檔案:

function changeImg(){<br /> //alert("in changeImg");<br /> var imgSrc = document.getElementById("imgObj");<br /> //alert(""+imgSrc);<br /> var oldsrc = imgSrc.src;<br /> //alert(""+oldsrc);<br /> var newsrc = chgUrl(oldsrc);<br /> //alert(""+newsrc);<br /> imgSrc.src = newsrc;<br /> }<br /> //時間戳記<br /> //為了使每次產生圖片不一致,即不讓瀏覽器讀緩衝,所以需要加上時間戳記<br /> function chgUrl(url){<br /> //alert("in chgUrl");<br /> var timestamp = (new Date()).valueOf();<br /> //alert(""+url);<br /> var postion = url.indexOf("?");<br /> //alert(""+postion);<br /> if(postion>=0){<br /> var suburl = url.substr(0,postion);<br /> //alert(""+ suburl);<br /> url = suburl + "?timestamp=" + timestamp;<br /> }else{<br /> url = url + "?timestamp=" + timestamp;<br /> }<br /> return url;<br /> } </p><p>function isRightCode(){<br /> var code = $("#veryCode").attr("value");<br /> //alert(code);<br /> code = "c=" + code;<br /> $.ajax({<br /> type:"post",<br /> url:"resultServlet",<br /> data:code,<br /> success:callback<br /> });<br />} </p><p>function callback(data){<br />$("#info").html(data);<br />}

 

相關文章

聯繫我們

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