-
总结: 验证码就是一张图,然后往这张图上写入随机的字符(数字字母等)。
1.1 编写html页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="servlet/yanzheng" method="post" >
验证码:<input type="text" name="userCode" /><img src="servlet/CheckCodeImages" /><br/>
<input type="submit" value="验证是否正确" />
</form>
</body>
</html>
1.2 生成验证码图片
- CheckCodeImages.java(对应url-patting为servlet/CheckCodeImages)
package servlet;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class CheckCodeImages
*
* 生成图片验证码
*/
public class CheckCodeImages extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public CheckCodeImages() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("image/jpeg"); //返回的是图像且后缀为jpeg
//从内存创建一张图片
BufferedImage bi=new BufferedImage(80, 40, BufferedImage.TYPE_3BYTE_BGR);
//拿到图的画笔
Graphics g=bi.getGraphics();
//获取图上面的图案,即验证码
String code=""; //4个数字合并的字符串
for(int i=0;i<4;i++){
Random rand=new Random();
String strCode=String.valueOf(rand.nextInt(10));
code+=strCode;
}
//将图案画在图上
g.drawString(code, 20, 20);
//将验证码存起来,以供验证
request.getSession().setAttribute("code", code);
//生成图片
ImageIO.write(bi, "jpeg", response.getOutputStream());
}
}
结果:
解析: 这个servlet是一张产生随机验证码的图片。
1.3 验证用户输入验证码是否正确
- yanzheng.java( <url-pattern>/servlet/yanzheng</url-pattern>)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
//得到用户输入的验证码
String userCode=request.getParameter("userCode");
//得到随机产生的验证码
String code=(String) request.getSession().getAttribute("code");
if(userCode.equals(code)){
System.out.println("验证码输入正确");
}else{
System.out.println("验证码输入错误");
}
}