验证码的随机生成
WEB.XML文件的配置
<servlet>
<servlet-name>ValidateColorServlet</servlet-name>
<!--生成验证码图片的类的路径-->
<servlet-class>com.ERP.system.filter.ValidateColorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ValidateColorServlet</servlet-name>
<!--注意斜杠不能少-->
<url-pattern>/ValidateColorServlet</url-pattern>
</servlet-mapping>
创建一个随机生成验证码的Servlet类ValidateColorServlet
package com.ERP.system.filter;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.rmi.ServerException;
import java.util.Random;
public class ValidateColorServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
StringBuffer randomCode = null;
private static final String CHECK_CODE_KEY = "CHECK_CODE_KEY";
//图片高度,宽度,验证码的个数
private int width = 152;
private int height = 40;
private int codeCount = 4;
//验证码字体的高度
private int fontHeight;
//验证码中的单个字符基线,即验证码中单个字符位于验证码图形左上角(codeX,codeY)位置处
private int codeX = 0;
private int codeY = 0;
//验证码由哪些字符组成
char []codeSequence = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890".toCharArray();
//初始化验证码图形属性
public void init()
{
fontHeight = height - 2;
codeX = width / (codeCount + 2);
codeY = height - 4;
}
public void service(HttpServletRequest request, HttpServletResponse response)throws ServerException, IOException
{
BufferedImage buffImg = null;
//TYPE_3BYTE_BGR表示具有8位RGB颜色分量的图像,对应于Windows风格的BGR颜色模型),蓝色,绿色和红色以3个字节存储。
buffImg = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
Graphics2D graphics = null;
graphics = buffImg.createGraphics();
graphics.setColor(Color.WHITE);
//填充一个指定的矩形
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.YELLOW);
for(int i = 0;i < 55;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 对象,用于保存随机产生的验证码,以便用户登录后验证
randomCode = new StringBuffer();
for(int i = 0;i < codeCount;i++)
{
String strRand = null;
strRand = String.valueOf(codeSequence[random.nextInt(62)]);
//把正在产生的随机字符放入StringBuffer中
randomCode.append(strRand);
graphics.setColor(Color.red);
graphics.drawString(strRand,(i + 1)*codeX,codeY);
} System.out.println(randomCode);
//再把存放有所有随机字符的StringBuffer对应的字符串放入到HttpSession中
request.getSession().setAttribute(CHECK_CODE_KEY,randomCode.toString());
//禁止图像缓存
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expirses", 0);
//将图像输出到输出流中
ServletOutputStream sos = null;
sos = response.getOutputStream();
ImageIO.write(buffImg, "jpeg", sos);
sos.close();
}
}
jSP页面获得验证码图片
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%--配置绝对路径--%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":"
+ request.getServerPort() + path + "/";
%>
<!DOCTYPE html>
<html>
<head>
<title>登录界面</title>
</head>
<body style="background:url(images/bg.jpg) no-repeat;">
<%--取得验证码图片--%>
<img src="<%=basePath%>/ValidateColorServlet" onclick="this.src=this.src+'?'+Math.random()" id="img">
<%--单击刷新验证码图片--%>
<a href="#" onclick="document.getElementById('img').onclick()">看不清换一张</a><br/>
<%--文本框输入可通过name传入后台--%>
<input type="text" name="yanzhenma" class="login_input" id="Password2" placeholder="请输入验证码(注意区分字母大小写)" />
</body>
</html>
后台登录Controller通过session拿到验证码的值
String yzm=(String)((HttpSession) session).getAttribute("CHECK_CODE_KEY");
登录Controller通过servlet拿到jsp页面文本框的值
request.getParameter("yanzhenma")