登入(帶驗證碼圖片)小案例,驗證碼案例
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>Title</title> 5 <script type="text/javascript"> 6 function _change() { 7 var imgEle = document.getElementById("image"); 8 imgEle.src = "/VerifyCodeServlet?a="+new Date().getTime(); 9 10 }11 </script>12 </head>13 <body>14 <%--本頁面提供登入表單,還要顯示錯誤資訊--%>15 <h1>登入</h1>16 <%17 /*18 讀取名為uname的cookie.19 如果為空白顯示:""20 如果不為空白顯示:Cookie的值21 */22 String uname = "";23 Cookie[] cs = request.getCookies();//擷取請求中所有的cookie24 if(cs != null) { //如果存在cookies25 for(Cookie c : cs) { //迴圈遍曆所有的cookie26 if("uname".equals(c.getName())){ //尋找名為uname的cookie27 uname = c.getValue();//擷取這個cookie的值,給uname這個變數28 }29 }30 }31 %>32 <%33 String message = "";34 String msg = (String) request.getAttribute("msg");//擷取request域中的名為msg的屬性35 if (msg!=null) {36 message = msg;37 }38 %>39 40 <font color="red"><b><%=message %></b></font>41 <form action="/LoginServlet" method="post">42 <%-- 把cookie中的使用者名稱顯示到使用者文字框中 --%>43 <table border="0">44 <tr>45 <td>使用者名稱:</td>46 <td><input type="text" name="username" value="<%=uname %>"size="15"/></td>47 </tr>48 <tr>49 <td>密 碼:</td>50 <td><input type="password" name="password" size="15"/>51 </td>52 </tr>53 <tr>54 <td>驗證碼:</td>55 <td><input type="text" name="verifyCode" size="6"/><img id="image" src="/VerifyCodeServlet">56 <a href="javascript:_change()">換一張</a>57 </td>58 </tr>59 </table>60 <br/>61 <input type="submit" value="登入"> 1 @WebServlet(name = "LoginServlet",urlPatterns = "/LoginServlet") 2 public class LoginServlet extends HttpServlet { 3 protected void doPost(HttpServletRequest request, HttpServletResponse response) 4 throws ServletException, IOException { 5 /* 6 *校正驗證碼 7 * 1、從session中擷取周期的驗證碼 8 * 2、從表單中擷取使用者填寫的驗證碼 9 * 3、進行比較10 * 4、如果相同,向下執行,否則儲存錯誤資訊到request域,轉寄到login.jsp11 * */12 String sessionCode = (String) request.getSession().getAttribute("session_vcode");13 String paramCode = request.getParameter("verifyCode");14 if (!paramCode.equalsIgnoreCase(sessionCode)) {15 request.setAttribute("msg","驗證碼錯誤!");16 request.getRequestDispatcher("/jsps/login.jsp").forward(request,response);17 return;18 }19 20 /*21 * 1、擷取表單資料22 * */23 request.setCharacterEncoding("utf-8");24 //擷取25 String username = request.getParameter("username");26 String password = request.getParameter("password");27 /*28 * 2、校正使用者名稱和密碼是否正確29 * */30 if (!"itcast".equalsIgnoreCase(username)) { //登入成功31 /*32 * 附加項:把使用者名稱儲存到cookie中,發送給用戶端瀏覽器33 * 當再次開啟login.jsp時,login.jsp中會讀取request中的cookie,把它顯示到使用者名稱文字框中34 * */35 Cookie cookie = new Cookie("uname",username);//建立cookie36 cookie.setMaxAge(60*60*24);//設定cookie命長為1天37 response.addCookie(cookie);38 /*39 * 3、如果成功40 * 儲存使用者資訊到session中41 * 重新導向到succ1.jsp42 * */43 HttpSession session = request.getSession();//擷取session44 session.setAttribute("username",username);//向session域中儲存使用者名稱45 response.sendRedirect("/jsps/succ1.jsp");46 }else { //登入失敗47 /*48 * 4、如果失敗49 * 儲存錯誤資訊到request域中50 * 轉寄到login.jsp51 * */52 request.setAttribute("msg","使用者或密碼錯誤");53 RequestDispatcher qr = request.getRequestDispatcher("/jsps/login.jsp");//得到轉寄站54 qr.forward(request,response);//轉寄55 }56 }57 58 protected void doGet(HttpServletRequest request, HttpServletResponse response)59 throws ServletException, IOException {60 doPost(request,response);61 }62 }
1 @WebServlet(name = "VerifyCodeServlet",urlPatterns = "/VerifyCodeServlet") 2 public class VerifyCodeServlet extends HttpServlet { 3 protected void doGet(HttpServletRequest request, HttpServletResponse response) 4 throws ServletException, IOException { 5 /* 6 * 1、儲存圖片 7 * 2、儲存圖片上的文本到session域中 8 * 3、把圖片響應給用戶端 9 * */10 VerifyCode vc = new VerifyCode();11 BufferedImage image = vc.getImage();12 request.getSession().setAttribute("session_vcode",vc.getText());//儲存圖片上的文本到session域中13 14 try {15 VerifyCode.output(image,response.getOutputStream());16 } catch (Exception e) {17 e.printStackTrace();18 }19 }20 }
1 /* 2 * 驗證碼圖片產生方法 3 * */ 4 public class VerifyCode { 5 private int w = 70; 6 private int h = 35; 7 private Random r = new Random(); 8 //可選的字型 9 private String[] fontNames = {"宋體","華文楷體","黑體","微軟雅黑","楷體_GB2312"};10 //可選的字元11 private String codes = "23456789abcdefghijklmnopqrstuvwsyzABCDEFGHIJKLMNOPQRSTUVWSYX";12 private Color bgColor = new Color(255,255,255);13 private String text;14 15 //產生隨機的顏色16 private Color randomColor() {17 int red = r.nextInt(150);18 int green = r.nextInt(150);19 int blue = r.nextInt(150);20 return new Color(red,green,blue);21 }22 23 //產生隨機字型24 private Font randomFont() {25 int index = r.nextInt(fontNames.length);26 String fontName = fontNames[index];//產生隨機的字型名稱27 int style = r.nextInt(4);//產生隨機的樣式,0(無樣式),1(粗體),2(斜體),3(粗體加斜體)28 int size = r.nextInt(5)+25;//產生隨機字型大小24-2829 return new Font(fontName,style,size);30 }31 32 //畫幹擾線33 private void drawLine(BufferedImage image) {34 int num = r.nextInt(6);35 Graphics2D g2 = (Graphics2D)image.getGraphics();36 for (int i = 0; i < num; i++) {//產生兩個點的座標,即4個值37 int x1 = r.nextInt(w);38 int y1 = r.nextInt(h);39 int x2 = r.nextInt(w);40 int y2 = r.nextInt(h);41 g2.setStroke(new BasicStroke(1.5F));42 g2.setColor(Color.BLUE);//幹擾線是藍色43 g2.drawLine(x1,y1,x2,y2);//畫線44 }45 }46 47 //產生隨機一個字元48 private char randomChar() {49 int index = r.nextInt(codes.length());50 return codes.charAt(index);51 }52 53 //建立一個BufferedImage54 private BufferedImage creatImage() {55 BufferedImage image = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);56 Graphics2D g2 = (Graphics2D) image.getGraphics();57 g2.setColor(this.bgColor);58 g2.fillRect(0,0,w,h);59 return image;60 }61 62 //調用這個方法得到驗證碼63 public BufferedImage getImage() {64 BufferedImage image = creatImage(); //建立圖片緩衝區65 Graphics2D g2 = (Graphics2D) image.getGraphics();//得到繪製環境66 StringBuilder sb = new StringBuilder();//用來裝載產生的驗證碼文本67 for (int i = 0; i <4 ; i++) {//迴圈四次,每次隨機產生一個字元68 String s = randomChar()+"";//隨機產生一個字元69 sb.append(s);//把字母添加到sb中70 float x = i * 1.0F * w / 4;//設定當前字元的x軸座標71 g2.setFont(randomFont());//設定隨機字型72 g2.setColor(randomColor());//設定隨機顏色73 g2.drawString(s,x,h-5);//畫圖74 }75 this.text = sb.toString();//把產生的字串賦給了this.text76 drawLine(image);//添加幹擾線77 return image;78 }79 //返回驗證碼圖片上的文本80 public String getText() {81 return text;82 }83 //儲存圖片到指定的輸出資料流84 public static void output (BufferedImage image, OutputStream out)85 throws Exception{86 ImageIO.write(image,"JPEG",out);87 }88 }
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>Title</title> 5 </head> 6 <body> 7 <h1>succ1</h1> 8 <% 9 String username = (String)session.getAttribute("username");10 if(username == null) {11 request.setAttribute("msg","您還沒有註冊");12 request.getRequestDispatcher("/jsps/login.jsp").forward(request,response);13 return;14 }15 %>16 歡迎<%=username %>17 </body>18 </html>