验证码生成
>生成图片(VerfiyCode类)
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
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(250, 250, 250);
// 用于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); //生成随机样式:0无样式,1粗体,2斜体,3粗+斜
int size = r.nextInt(5) + 24; //生成随机字号
return new Font(fontName, style, size);
}
// 画干扰线
private void drawLine(BufferedImage image) {
int num = 3; //一共画3条
Graphics2D g2 = (Graphics2D) image.getGraphics();
for (int i = 0; i < num; i++) { //生成两个点的坐标,即4个值
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);
}
}
测试类:
public class test {
public static void main(String[] args) throws IOException {
VerifyCode code = new VerifyCode();
BufferedImage image = code.createImage();
ImageIO.write(image,"jpg",new File("F:/image.jpg"));
}
}
>在用户登录案例中添加入验证码:防止恶意注册(自动注册的程序无法识别验证码)
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/VerifyCodeServlet")
public class VerifyCodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/**
* 1.生成图片
* 2.保存图片上的文本到session中
* 3.把图片响应给客户端
*/
VerifyCode vc = new VerifyCode() ;
BufferedImage image = vc.createImage() ;
request.getSession().setAttribute("session_vcode", vc.getText());
VerifyCode.output(image, response.getOutputStream());
}
}
在ALoginServlet中添加:
//附加:校验验证码
String sessionCode = (String)request.getAttribute("session_vcode") ;
String paramCode = request.getParameter("verifyCode") ;
if(!paramCode.equalsIgnoreCase(sessionCode)) {
request.setAttribute("msg", "验证码错误!");
request.getRequestDispatcher("/Session/login.jsp").forward(request, response);
return; //出现错误后不再向下转型
}
在jsp页面中:
<script type="text/javascript">
function _change() {
var imgEle = document.getElementById("img");
//加参数是因为:如果不加参数,在点击换一张时,浏览器会直接使用上次缓存的图片,不会重新加载。添加一个时间参数保证了每次要加载的图片都不一样,不能从缓存中获取
imgEle.src = "/ali_web/VerifyCodeServlet?a=" + new Date().getTime() ;
}
</script>
——————————————————————
<form action="/ali_web/ALoginServlet" method="post">
用户名:<input type="text" name="username" value="<%=uname %>" /><br/>
密 码:<input type="password" name="password" /><br/>
验证码:<input type="text" name="verifyCode"/>
<img id="img" src="/ali_web/VerifyCodeServlet">
<a href="javascript:_change()">看不清,换一张</a>
<input type="submit" value="登录" />
</form>