JSP实现生成验证码

时间:2022-12-29 21:00:46

话不多说上代码Jsp,具体验证码图片可以在发挥

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
<%--该页面主要生成验证码 --%>
<%!
//定义静态常量,表示验证码可以显示的字符
static ArrayList<Character> codeMembers;
static {
//初始化
codeMembers=new ArrayList<Character>();
for(int i='A';i<='Z';i++){
codeMembers.add((char)i);
}
for(int i='0';i<='9';i++){
codeMembers.add((char)i);
}
}
%>
<%!
//生成随机颜色
public Color getColor(){
Random random=new Random();
int r=random.nextInt(256);//生成0-255随机数
int g=random.nextInt(256);
int b=random.nextInt(256);
return new Color(r,g,b);

}
//生成4为随机验证码
public String getCode(){
Random random=new Random();
String res="";
//得到4为的验证码,且只包含字母和数字
for(int i=0;i<4;i++){
int index=random.nextInt(codeMembers.size());//
char c=codeMembers.get(index);
res+=c;
}
return res;
}

%>
<%
response.setHeader("pragma", "mo-cache");
response.setHeader("cache-control", "no-cache");
response.setDateHeader("expires", 0);

BufferedImage image=new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics();
g.setColor(new Color(200,200,200));
g.fillRect(0,0,80,30);

//画干扰背景
for(int i=0;i<30;i++){
Random random=new Random();
//起点坐标
int x1=random.nextInt(80);
int y1=random.nextInt(30);
//终点
int x2=random.nextInt(x1+10);
int y2=random.nextInt(y1+10);
g.setColor(getColor());
g.drawLine(x1,y1,x1+x2,y1+y2);
}

//验证码信息
g.setFont(new Font("serif",Font.BOLD,16));
g.setColor(Color.BLACK);
//得到验证码字符串
String code=getCode();
//处理字符串,加空格
StringBuffer sb=new StringBuffer();
for(int i=0;i<code.length();i++){
sb.append(code.charAt(i)+" ");
}
//画
g.drawString(sb.toString().toUpperCase(),15,20);
//重点:将验证码信息加入Session域
session.setAttribute("CHECKCODE",code);

ImageIO.write(image,"jpeg",response.getOutputStream());
out.clear();
out=pageContext.pushBody();
System.out.println(session.getAttribute("CHECKCODE"));

%>