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
相关文章
相关标签/搜索