**学习HttpServlet的小案例,验证码动态更新、及提交验证。
一、建立java项目后,在web项下建的html如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>验证码案例</title>
</head>
<body>
<form action="/cookieServlet/RegisterServlet" method="post">
<input type="text" name="vCode"/>
<img alt="图片" id="vCode" src="/cookieServlet/VerifyCodeServlet"/>
<a href="javascript:change()">看不清,换一张</a>
<input type="submit" value="提交">
</form>
</body>
<script type="text/javascript">
function change() {
var vCode = document.getElementById("vCode");
vCode.src="/cookieServlet/VerifyCodeServlet?"+new Date().getTime();
}
</script>
</html>
二、创建类包,编写java代码:
2.1 随机验证码的背景文字及干扰信息等(写好的代码直接导入):
package codeDemo
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
public class VerifyCode {
private int w = 70;
private int h = 35;
private Random r = new Random();
// 定义有那些字体
private String[] fontNames = { "宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312" };
// 定义有那些验证码的随机字符
private String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
// 生成背景色
private Color bgColor = new Color(200, 100, 50);
// 用于gettext 方法 获得生成的验证码文本
private String text;
// 生成随机颜色
private Color randomColor() {
int red = r.nextInt(150);
int green = r.nextInt(150);
int blue = r.nextInt(150);
return new Color(red, green, blue);
}
// 生成随机字体
private Font randomFont() {
int index = r.nextInt(fontNames.length);
String fontName = fontNames[index];
int style = r.nextInt(4);
int size = r.nextInt(5) + 24;
return new Font(fontName, style, size);
}
// 画干扰线
private void drawLine(BufferedImage image) {
int num = 3;
Graphics2D g2 = (Graphics2D) image.getGraphics();
for (int i = 0; i < num; i++) {
int x1 = r.nextInt(w);
int y1 = r.nextInt(h);
int x2 = r.nextInt(w);
int y2 = r.nextInt(h);
g2.setStroke(new BasicStroke(1.5F));// 不知道
g2.setColor(Color.blue);
g2.drawLine(x1, y1, x2, y2);
}
}
// 得到codes的长度内的随机数 并使用charAt 取得随机数位置上的codes中的字符
private char randomChar() {
int index = r.nextInt(codes.length());
return codes.charAt(index);
}
// 创建一张验证码的图片
public BufferedImage createImage() {
BufferedImage image = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) image.getGraphics();
StringBuilder sb = new StringBuilder();
// 向图中画四个字符
for (int i = 0; i < 4; i++) {
String s = randomChar() + "";
sb.append(s);
float x = i * 1.0F * w / 4;
g2.setFont(randomFont());
g2.setColor(randomColor());
g2.drawString(s, x, h - 5);
}
this.text = sb.toString();
drawLine(image);
// 返回图片
return image;
}
// 得到验证码的文本 后面是用来和用户输入的验证码 检测用
public String getText() {
return text;
}
// 定义输出的对象和输出的方向
public static void output(BufferedImage bi, OutputStream fos)
throws FileNotFoundException, IOException {
ImageIO.write(bi, "JPEG", fos);
}
}
2.2 获取验证码上的文本、图片等代码:
package codeDemo;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class VerifyCodeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//创建验证码类对象
VerifyCode vc=new VerifyCode();
//获取图片
BufferedImage image = vc.createImage();
//获取文本
String text = vc.getText();
//设置session域数据
HttpSession session = req.getSession();
session.setAttribute("text",text);
//获取输出流
ServletOutputStream outputStream = resp.getOutputStream();
//把图片响应到页面去
vc.output(image,outputStream);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doPost(req, resp);
}
}
2.3 判断验证码上的文本和输入的文本,
package codeDemo;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class RegisterServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//设定字符集
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
//获取验证码文本
String vCode = req.getParameter("vCode");
//判断输入和随机产生的是否相同
//图片中的验证码怎么获取,在verifycodeservlet类中
//verifycodeservlet和registservlet要共享数据,不在一个请求中,但在一个会话中
//用session会话共享数据
//获取数据
HttpSession session = req.getSession();
String text = (String) session.getAttribute("text");
String msg="";
//判断
if (vCode.equalsIgnoreCase(text)) {
msg = "验证成功!";
}else {
msg="验证码错误!";
}
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().println(msg);
}
}
三、别忘记在xml中注册两个servlet:
<!--表单提交的servlet注册-->
<servlet>
<servlet-name>codeServlet1</servlet-name>
<servlet-class>codeDemo.VerifyCodeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>codeServlet1</servlet-name>
<url-pattern>/VerifyCodeServlet</url-pattern>
</servlet-mapping>
<!--随机验证码的servlet注册-->
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>codeDemo.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet</url-pattern>
</servlet-mapping>