1. 程式人生 > >登錄(帶驗證碼圖片)小案例

登錄(帶驗證碼圖片)小案例

this rgb equals param dex gre type size image

 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();//獲取請求中所有的cookie
24     if(cs != null) { //如果存在cookies
25       for(Cookie c : cs) { //循環遍歷所有的cookie
26         if("uname".equals(c.getName())){ //查找名為uname的cookie
27             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="登錄" style="color: black">
62     </form>
63 </body>
64 </html>
 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.jsp
11         * */
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);//創建cookie
36             cookie.setMaxAge(60*60*24);//設置cookie命長為1天
37             response.addCookie(cookie);
38             /*
39             * 3、如果成功
40             *   保存用戶信息到session中
41             *   重定向到succ1.jsp
42             * */
43             HttpSession session = request.getSession();//獲取session
44             session.setAttribute("username",username);//向session域中保存用戶名
45             response.sendRedirect("/jsps/succ1.jsp");
46         }else { //登錄失敗
47             /*
48             * 4、如果失敗
49             *   保存錯誤信息到request域中
50             *   轉發到login.jsp
51             * */
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-28
29         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     //創建一個BufferedImage
54     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.text
76         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>

登錄(帶驗證碼圖片)小案例