目录结构:
index.jsp
<%@ page language="java" pageEncoding="utf-8"%>
<html>
<script type="text/javascript">
function refresh(){
document.getElementById("img").src="/VerificationCode/generate?"+Math.random();
//必须加Math.random(),否则由于地址未改变,浏览器不会去请求Servlet
}
</script>
<head>
<title>验证码的使用</title>
</head>
<body>
<form action="/VerificationCode/check" method="post">
内 容:<input type=text name=message><br>
验证码:<input type=text name=chkmsg><img id="img" src="/VerificationCode/generate"></img><a href="javascript:void(0)" οnclick="refresh()">看不清,换一张</a><br>
<input type=submit value="确定"> <input type=reset value="重置">
</form>
</body>
<html>
GenerateVerificationServlet.java
package com.yourcompany.servlet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class GenerateVerificationServlet extends HttpServlet{
//生成4位在一定取值范围的随机字符
public char[] getRandom() {
char[] rand=new char[4];
String str1="0123456789";
String str2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
int length1 =str1.length();
int length2 =str2.length();
Random rd=new Random();
int index1 = rd.nextInt(length1);
int index2 = rd.nextInt(length2);
int index3 = rd.nextInt(length1);
int index4 = rd.nextInt(length2);
rand[0]=str1.charAt(index1);
rand[1]=str2.charAt(index2);
rand[2]=str1.charAt(index3);
rand[3]=str2.charAt(index4);
return rand;
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置响应内容类型
response.setContentType("image/jpeg");
//创建字节流
ServletOutputStream sos=response.getOutputStream();
//设置缓冲区
BufferedImage img=new BufferedImage(60,30,4);
//在缓冲区中绘图
Graphics g=img.getGraphics();
//调生成4位随机数的方法
char[] rand=this.getRandom();
//保存于session中,以便其它页面可用
request.getSession().setAttribute("chkmsg", new String(rand));
//画3条干扰线
g.setColor(Color.red);
g.drawLine(new Random().nextInt(60), new Random().nextInt(60), new Random().nextInt(20), new Random().nextInt(20));
g.drawLine(new Random().nextInt(60), new Random().nextInt(60), new Random().nextInt(60), new Random().nextInt(20));
g.drawLine(new Random().nextInt(80), new Random().nextInt(60), new Random().nextInt(50), new Random().nextInt(20));
//画背景色
g.drawRect(0, 0, 60, 30);
g.setColor(Color.blue);
//设置前景色
g.setColor(Color.green);
g.drawString(""+rand[0], 5, 20);
g.drawString(""+rand[1], 20, 10);
g.drawString(""+rand[2], 30, 15);
g.drawString(""+rand[3], 50, 20);
//关闭
g.dispose();
JPEGImageEncoder code=JPEGCodec.createJPEGEncoder(sos);
code.encode(img);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
this.doGet(request, response);
}
}
CheckVerificationServlet.java
package com.yourcompany.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CheckVerificationServlet extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置编码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
//获取输入的其他信息
String message = request.getParameter("message");
//获取输入的验证码
String chkmsg = request.getParameter("chkmsg");
//获取正确的验证码
String rand = (String) request.getSession().getAttribute("chkmsg");
//判断验证码是否正确
if(chkmsg!=null && rand!=null){
if(chkmsg.equals(rand)) {
out.println(message);
out.println("成功");
} else {
out.println(message);
out.println("失败");
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>GenerateVerificationServlet</servlet-name>
<servlet-class>com.yourcompany.servlet.GenerateVerificationServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>CheckVerificationServlet</servlet-name>
<servlet-class>com.yourcompany.servlet.CheckVerificationServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GenerateVerificationServlet</servlet-name>
<url-pattern>/generate</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>CheckVerificationServlet</servlet-name>
<url-pattern>/check</url-pattern>
</servlet-mapping>
</web-app>