<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--
1. 要求输入验证码
2. 在目标 Servlet 中验证验证码输入的是否正确, 若正确, 响应 success.jsp 页面; 若不正确, 返回 login.jsp
页面, 提示用户 "验证码错误", 并重新输入
-->
<font color="red">${requestScope.errormsg }</font>
<br><br>
<form action="LoginServlet" method="post">
<table>
<tr>
<td>Name: </td>
<td><input name="name" type="text"/></td>
</tr>
<tr>
<td>Password: </td>
<td><input name="password" type="password"/></td>
</tr>
<tr>
<td>Code: </td>
<td><img src="ValidateColorServlet" alt=""/></td>
</tr>
<tr>
<td>Confirm Code: </td>
<td><input name="code" type="text"/><font color="red">验证码区分大小写</font>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
注册成功!
</body>
</html>
package com.syh.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ValidateColorServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response) ;
}
// 生成数字和字母的验证码
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
service(request, response) ;
/*
//第一种产生随即验证码的方式 ,在采用第三种方式生成验证码的时候要将第一种和第二种方式都注释了
BufferedImage img = new BufferedImage(68, 22,
BufferedImage.TYPE_INT_RGB);
// 得到该图片的绘图对象
Graphics g = img.getGraphics();
Random r = new Random();
Color c = new Color(200, 150, 255);
g.setColor(c);
// 填充整个图片的颜色
g.fillRect(0, 0, 68, 22);
// 向图片中输出数字和字母
StringBuffer sb = new StringBuffer();
char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
int index, len = ch.length;
for (int i = 0; i < 4; i ++) {
index = r.nextInt(len);
g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt
(255)));
g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 22));// 输出的字体和大小
g.drawString("" + ch[index], (i * 15) + 3, 18);//写什么数字,在图片的什么位置画
sb.append(ch[index]);
}
request.getSession().setAttribute("randomCode", randomCode.toString());
ImageIO.write(img, "JPG", response.getOutputStream());
} */
/*
//第二种产生随即验证码的方式 ,在采用第三种方式生成验证码的时候要将第一种和第二种方式都注释了
int width=150;//验证码图片宽度
int height=60;//验证码图片高度
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
Graphics g=image.getGraphics();
Random random=new Random();//创建一个随机类
g.setColor(getRandColor(200,250));//背景颜色要偏淡
g.fillRect(0, 0, width, height);//画背景
g.setColor(getRandColor(0,255));//边框颜色
g.drawRect(0, 0, width-1, height-1);//画边框
g.setColor(getRandColor(160,200));// 随机产生5条干扰线,使图象中的认证码不易被其它程序探测到
for(int i=0;i<8;i++){
int x=random.nextInt(width);
int y=random.nextInt(height);
int x1=random.nextInt(width);
int y1=random.nextInt(height);
g.drawLine(x, y, x1, y1);
}
g.setColor(getRandColor(160,200));// 随机产生100点,使图象中的认证码不易被其它程序探测到
for(int i=0;i<100;i++){
int x=random.nextInt(width);
int y=random.nextInt(height);
g.drawLine(x, y, x, y);
}
Font font = new Font("Times New Roman", Font.ITALIC,38); // 创建字体,字体的大小应该根据图片的高度来定。
g.setFont(font);//设置字体
int length = 6; // 设置默认生成4个验证码
String s="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // 设置备选验证码:包括"a-z"和数字"0-9"
String sRand="";
// 用随机产生的颜色将验证码绘制到图像中。
// 生成随机颜色(因为是做前景,所以偏深)
//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
for(int i=0;i<length;i++){
String ch=String .valueOf(s.charAt(random.nextInt(s.length())));
sRand+=ch;
g.drawString(ch, 22*i+12, (random.nextInt(5)-2)*i+40);
}
//将生成的字符串存储在session中
HttpSession session=request.getSession();
session.setAttribute("randomCode", randomCode.toString());
g.dispose();//图像生效
//禁止图像缓存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
//创建二进制的输出流
ServletOutputStream sos=response.getOutputStream();
// 将图像输出到Servlet输出流中。
ImageIO.write(image, "jpeg", sos);
sos.flush();
sos.close();
}
public Color getRandColor(int lower,int upper){
Random random = new Random();
if(upper>255)
upper=255;
if(upper<1)
upper=1;
if(lower<1)
lower=1;
if(lower>255)
lower=255;
int r=lower+random.nextInt(upper-lower);
int g=lower+random.nextInt(upper-lower);
int b=lower+random.nextInt(upper-lower);
return new Color(r,g,b);
} */
}
//第三种产生验证码的方式
//设置验证图片的宽度, 高度, 验证码的个数
private int width = 152;
private int height = 40;
private int codeCount = 4;
//验证码字体的高度
private int fontHeight = 4;
//验证码中的单个字符基线. 即:验证码中的单个字符位于验证码图形左上角的 (codeX, codeY) 位置处
private int codeX = 0;
private int codeY = 0;
//验证码由哪些字符组成
char [] codeSequence = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz23456789".toCharArray();
//初始化验证码图形属性
public void init(){
fontHeight = height - 2;
codeX = width / (codeCount + 2);
codeY = height - 4;
}
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//定义一个类型为 BufferedImage.TYPE_INT_BGR 类型的图像缓存
BufferedImage buffImg = null;
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
//在 buffImg 中创建一个 Graphics2D 图像
Graphics2D graphics = null;
graphics = buffImg.createGraphics();
//设置一个颜色, 使 Graphics2D 对象的后续图形使用这个颜色
graphics.setColor(Color.WHITE);
//填充一个指定的矩形: x - 要填充矩形的 x 坐标; y - 要填充矩形的 y 坐标; width - 要填充矩形的宽度; height - 要填充矩形的高度
graphics.fillRect(0, 0, width, height);
//创建一个 Font 对象: name - 字体名称; style - Font 的样式常量; size - Font 的点大小
Font font = null;
font = new Font("", Font.BOLD, fontHeight);
//使 Graphics2D 对象的后续图形使用此字体
graphics.setFont(font);
graphics.setColor(Color.BLACK);
//绘制指定矩形的边框, 绘制出的矩形将比构件宽一个也高一个像素
graphics.drawRect(0, 0, width - 1, height - 1);
//随机产生 15 条干扰线, 使图像中的认证码不易被其它程序探测到
Random random = null;
random = new Random();
graphics.setColor(Color.GREEN);
for(int i = 0; i < 20; i++){
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(20);
int y1 = random.nextInt(20);
graphics.drawLine(x, y, x + x1, y + y1);
}
//创建 randomCode 对象, 用于保存随机产生的验证码, 以便用户登录后进行验证
StringBuffer randomCode;
randomCode = new StringBuffer();
for(int i = 0; i < codeCount; i++){
//得到随机产生的验证码数字
String strRand = null;
strRand = String.valueOf(codeSequence[random.nextInt(36)]);
//用随机产生的颜色将验证码绘制到图像中
graphics.setColor(Color.BLUE);
graphics.drawString(strRand, (i + 1)* codeX, codeY);
randomCode.append(strRand);
}
request.getSession().setAttribute("randomCode", randomCode.toString());
//禁止图像缓存
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
//将图像输出到输出流中
ServletOutputStream sos = null;
sos = response.getOutputStream();
ImageIO.write(buffImg, "jpeg", sos);
sos.close();
}
}
package com.syh.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String paramCode = request.getParameter("code") ;
HttpSession session = request.getSession() ;
String sessionCode = (String) session.getAttribute("randomCode") ;
//这里的验证码是区分大小写的!
if(paramCode.equals(sessionCode)) {
response.sendRedirect(request.getContextPath() + "/success.jsp") ;
}else {
request.setAttribute("errormsg", "您输入的验证码不正确,请刷新页面后再次输入") ;
request.getRequestDispatcher("/login.jsp").forward(request, response) ;
return ;
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<servlet>
<servlet-name>ValidateColorServlet</servlet-name>
<servlet-class>com.syh.servlet.ValidateColorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ValidateColorServlet</servlet-name>
<url-pattern>/ValidateColorServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.syh.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>