You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
2.0 KiB
70 lines
2.0 KiB
<%@page import="java.awt.image.BufferedImage"%>
|
|
<%@page import="java.awt.*"%>
|
|
<%@page import="java.util.*"%>
|
|
<%@page import="javax.imageio.ImageIO" %>
|
|
<%@ page language="java" contentType="image/jpeg; charset=UTF-8"
|
|
pageEncoding="UTF-8"%>
|
|
<%!
|
|
//产生随机颜色
|
|
public Color getColor(){
|
|
Random ran=new Random();//random和math.random区别
|
|
int r=ran.nextInt(256);
|
|
int g=ran.nextInt(256);
|
|
int b=ran.nextInt(256);
|
|
return new Color(r,g,b);
|
|
}
|
|
//产生验证码的值
|
|
public String getNum(){
|
|
//0~8999 -> 1000~9999
|
|
int ran=(int)(Math.random()*9000)+1000;
|
|
return String.valueOf(ran);
|
|
}
|
|
|
|
|
|
|
|
%>
|
|
|
|
<%
|
|
|
|
//禁止缓存 防止验证码过期
|
|
response.setHeader("Pragma","no-cache");
|
|
response.setHeader("Cache-Control","no-cache");
|
|
response.setHeader("Expires","0");
|
|
//绘制验证码图片
|
|
BufferedImage image=new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB);
|
|
Graphics graphics=image.getGraphics();
|
|
graphics.fillRect(0,0,80,30);
|
|
|
|
//绘制验证码
|
|
graphics.setFont(new Font("seif",Font.BOLD,20));
|
|
graphics.setColor(Color.black);
|
|
String checkcode=getNum();
|
|
StringBuffer sb=new StringBuffer();
|
|
|
|
for(int i=0;i<checkcode.length();i++){
|
|
sb.append(checkcode.charAt(i)+" ");//获取验证码的每一位数字1 2 3 4...
|
|
}
|
|
//绘制验证码并调整位置
|
|
graphics.drawString(sb.toString(), 15, 20);
|
|
|
|
//绘制干扰线条
|
|
for(int i=0;i<60;i++){
|
|
Random ran=new Random();
|
|
|
|
int xBegin=ran.nextInt(80);
|
|
int yBegin=ran.nextInt(30);
|
|
int xEnd=ran.nextInt(xBegin+10);
|
|
int yEnd=ran.nextInt(yBegin+10);
|
|
graphics.setColor(getColor());
|
|
graphics.drawLine(xBegin, yBegin, xEnd, yEnd);
|
|
}
|
|
|
|
//验证码的真实值用于服务器后台验证
|
|
session.setAttribute("CHECKCODE", checkcode);
|
|
//产生图片
|
|
ImageIO.write(image,"jpeg",response.getOutputStream());
|
|
out.clear();
|
|
out=pageContext.pushBody();
|
|
//将image加入input src中<input type="iamge" src="..."/>
|
|
|
|
%> |