Servlet驗證碼的生成與使用

 電飯鍋  發的g

 

//
//  LoginViewController.m
//  Contact
//
//  Created by Jiexiang on 15/11/15.
//  Copyright © 2015年 Jiexiang. All rights reserved.
//

#import "LoginViewController.h"
#import "MBProgressHUD+MJ.h"

@interface LoginViewController ()
@property (weak, nonatomic) IBOutlet UITextField *nameField;
@property (weak, nonatomic) IBOutlet UITextField *pwdField;
@property (weak, nonatomic) IBOutlet UIButton *btnLogin;
- (IBAction)btnLoginAction;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 添加觀察者
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(txtChange) name:UITextFieldTextDidChangeNotification object:self.nameField];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(txtChange) name:UITextFieldTextDidChangeNotification object:self.pwdField];
}

- (void)txtChange {
    self.btnLogin.enabled = (self.nameField.text.length && self.pwdField.text.length);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

// 點擊了登陸
- (IBAction)btnLoginAction {
    if (![self.nameField.text isEqualToString:@"admin"]) {
        [MBProgressHUD showError:@"帳號不正確"];
        return;
    }
    if(![self.pwdField.text isEqualToString:@"123"]) {
        [MBProgressHUD showError:@"密碼錯誤"];
        return;
    }
    // 顯示遮罩
    [MBProgressHUD showMessage:@"加載中"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUD];
        // 根據關鍵字跳轉
        [self performSegueWithIdentifier:@"toContact" sender:nil];
    });
}
@end

 

1、新建Web項目,新建一個Servlet,取名:YZM.javahtml

注意:驗證碼裏面設置了Session的名字以及它的值java

在WEB.xml裏面對這個Servlet進行申明:apache

<servlet>
<servlet-name>YZM</servlet-name>
<servlet-class>YZM</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>YZM</servlet-name>
<url-pattern>/YZM</url-pattern>
</servlet-mapping>session

 1 import java.awt.Color;
 2 import java.awt.Font;
 3 import java.awt.Graphics;
 4 import java.awt.image.BufferedImage;
 5 import java.io.IOException;
 6 import java.util.Random;
 7 import javax.imageio.ImageIO;
 8 import javax.servlet.ServletException;
 9 import javax.servlet.annotation.WebServlet;
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 import javax.servlet.http.HttpSession;
14 @WebServlet("/YZM")
15 public class YZM extends HttpServlet {
16     private static final String CONTENT_TYPE = "text/html; charset=utf-8";  
17     
18     //設置字母的大小,大小  
19     private Font mFont = new Font("Arial", Font.BOLD, 18);
20     public void init() throws ServletException
21     {  
22         super.init();  
23     }  
24     
25     //去隨機顏色
26     Color getRandColor(int fc,int bc)  
27     {  
28         Random random = new Random();  
29         if(fc>255) fc=255;  
30         if(bc>255) bc=255;  
31         int r=fc+random.nextInt(bc-fc);  
32         int g=fc+random.nextInt(bc-fc);  
33         int b=fc+random.nextInt(bc-fc);  
34         return new Color(r,g,b);  
35     }  
36   
37     public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  
38     {  
39         response.setHeader("Pragma","No-cache");  
40         response.setHeader("Cache-Control","no-cache");  
41         response.setDateHeader("Expires", 0);  
42         //代表生成的響應是圖片  
43         response.setContentType("image/jpeg");  
44         
45         int width=80, height=18;  
46         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
47           
48         Graphics g = image.getGraphics();  
49         Random random = new Random();  
50         g.setColor(getRandColor(200,250));  
51         g.fillRect(1, 1, width-1, height-1);  
52         g.setColor(new Color(102,102,102));  
53         g.drawRect(0, 0, width-1, height-1);  
54         g.setFont(mFont);  
55         g.setColor(getRandColor(160,200));  
56   
57         //畫隨機線  
58         for (int i=0;i<155;i++)  
59         {  
60             int x = random.nextInt(width - 1);  
61             int y = random.nextInt(height - 1);  
62             int xl = random.nextInt(6) + 1;  
63             int yl = random.nextInt(12) + 1;  
64             g.drawLine(x,y,x + xl,y + yl);  
65         }  
66   
67         //從另外一方向畫隨機線  
68         for (int i = 0;i < 70;i++)  
69         {  
70             int x = random.nextInt(width - 1);  
71             int y = random.nextInt(height - 1);  
72             int xl = random.nextInt(12) + 1;  
73             int yl = random.nextInt(6) + 1;  
74             g.drawLine(x,y,x - xl,y - yl);  
75         }  
76   
77         //生成隨機數,並將隨機數字轉換爲字母  
78         String sRand="";  
79         for (int i=0;i<4;i++)  
80         {  
81             int itmp = random.nextInt(26) + 65;  
82             char ctmp = (char)itmp;  
83             sRand += String.valueOf(ctmp);  
84             g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));  
85             g.drawString(String.valueOf(ctmp),15*i+10,16);  
86         }  
87   
88         HttpSession session = request.getSession(true); 
89         //把放入Seession的值改爲小寫
90         sRand = sRand.toLowerCase();
91         
92         session.setAttribute("rand",sRand);  
93         g.dispose();
94         ImageIO.write(image, "JPEG", response.getOutputStream());  
95     }  
96 }

2、新建一個JSP文件,index.jspapp

着重注意:第11行如何對剛纔建立的驗證碼圖片進行引用,dom

title="點擊刷新" 做用:鼠標移到上面會現實提示
style=cursor:pointer 做用:鼠標移到上面改變鼠標的圖標
onclick="this.src=this.src" 做用:可實現點擊刷新
 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     <!-- 引用驗證碼 -->
11     <img title="點擊刷新" style=cursor:pointer onclick="this.src=this.src" src="YZM"/>
12     
13     <!-- 簡單的一個表單,測試下驗證碼 -->
14     <form action="checkLogin" method="post">
15         <input type="text" name="yzm"/>
16         <input type="submit" value="提交"/>
17     </form>
18 </body>
19 </html>

3、再建立一個Servlet對錶單裏輸入的驗證碼進行判斷jsp

在WEB.xml裏面對這個Servlet進行申明:ide

<servlet>
<servlet-name>checkLogin</servlet-name>
<servlet-class>checkLogin</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>checkLogin</servlet-name>
<url-pattern>/checkLogin</url-pattern>post

</servlet-mapping>測試

 

 1 import java.io.IOException;
 2 import java.io.PrintWriter;
 3 
 4 import javax.servlet.ServletException;
 5 import javax.servlet.annotation.WebServlet;
 6 import javax.servlet.http.HttpServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 import javax.servlet.http.HttpSession;
10 
11 import org.apache.catalina.connector.Request;
12 
13 @WebServlet("/checkLogin")
14 public class checkLogin extends HttpServlet {
15     private static final long serialVersionUID = 1L;
16 
17     public checkLogin() {
18         super();
19     }
20     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
21         response.setContentType("text/html;charset=utf-8");
22         request.setCharacterEncoding("utf-8");
23         PrintWriter out = response.getWriter();
24         
25         //獲取Session
26         HttpSession yzmSession = request.getSession();
27         
28         //獲取用戶輸入的驗證碼
29         String yzm = request.getParameter("yzm");
30         String systemYzm= (String)yzmSession.getAttribute("rand");
31         
32         out.print("systemYzm = " + systemYzm);
33         out.print("\n");
34         out.print("yzm = " + yzm);
35         out.print("\n");
36         
37         if(systemYzm.equals(yzm)){
38             out.print("驗證碼輸入正確\n");
39         }else{
40             out.print("驗證碼輸入錯誤\n");
41         }
42     }
43 
44
相關文章
相關標籤/搜索