繼上一篇為大家補充過濾器類后,本篇為大家簡單介紹一下如何實現驗證碼效果。驗證碼的作用是什么呢?1、防止惡意注冊2、防止惡意提交3、防止盜取賬戶等等,總的來說驗證碼的存在就是為了,防止非人為的操作,不過需要指出的是驗證碼是一種影響用戶體驗的功能,所以一些網站通過設置參數,當用戶第一次操作失敗后,才會提示用戶輸入驗證碼,這可以說是驗證碼的一種提高。不說這沒有用的了,下面我們開始實現我們的驗證碼效果。
1、實現效果圖:
2、index.jsp:
在這個界面設計時添加了一些javaScript的操作,如有疑問,可以留言。
<%@ 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>驗證碼</title> <meta http-equiv="Words" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/CSS" href="styles.css"> --> <script type="text/Javascript"> function reloadCode(){ var time = new Date().getTime();//通過這個來保證瀏覽器刷新界面 document.getElementById("img").src="<%=request.getContextPath() %>/servlet/ImgSelect?time="+time;//驗證更新操作 document.getElementById("code").value=""; document.getElementById("code").focus(); } </script> </head> <body> <center> <h1>驗證碼</h1> <form action="<%=request.getContextPath() %>/servlet/loginSelect" method="post"> <input type="text" id="code" name="code"/><img alt="驗證碼" id="img" src="<%=request.getContextPath() %>/servlet/ImgSelect"> <a href="javascript:reloadCode()" >看不清</a><br/> <input type="submit" value="提交"> </form> </center> </body></html>
3、生成驗證碼select:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB); Graphics g = bi.getGraphics(); Color color = new Color(200, 130, 255); g.setColor(color); g.fillRect(0, 0, 68, 22); char [] ch = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890zxcvbnmlkjhgfdsaqwertyuiop".toCharArray(); Random r = new Random(); StringBuffer buf = new StringBuffer(); int len = 0; for(int i=0; i<4; i++){ len = r.nextInt(ch.length); g.setColor(new Color(r.nextInt(150), r.nextInt(255), r.nextInt(200))); g.drawString(ch[len]+"", (i*15)+3, 18); buf.append(ch[len]); } String code = buf.toString(); request.getsession().setAttribute("code", code); ImageIO.write(bi, "JPG", response.getOutputStream()); }
4、驗證selelct:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); String code = request.getParameter("code"); String imgCode = (String) request.getSession().getAttribute("code"); if(imgCode.equalsIgnoreCase(code)){ out.println("登錄成功"); }else{ out.println("登錄失敗"); } }
到這里我們的驗證碼效果就實現了,對于生成漢字驗證碼、數學算式表達式的驗證碼效果大家就自行研究吧,思想已經為大家介紹完畢,對于JSP的總結,目前就差關于文件的上傳和下載了,估計會在隨后的日子里為大家分享,當然如果你能實現,還望多多指點。
新聞熱點
疑難解答