在jsp上开发验证码,代码如下
```bash
<%@ page language="java" import="java.io.File" pageEncoding="utf-8"%>
<%@ page import="java.awt.*"%>
<%@ page import="java.awt.image.BufferedImage"%>
<%@ page import="java.util.*"%>
<%@ page import="javax.imageio.ImageIO"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<%
response.setHeader("Cache-Control", "no-cache");
int width=60,height=20;
//在内存中创建画像
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//获取画笔
Graphics g=image.getGraphics();
//设置背景色
g.setColor(new Color(200,200,200));
g.fillRect(0,0,width,height);
Random rnd=new Random();
//随机产生四位随机数
int randNum=rnd.nextInt(8999)+1000;
String randStr=String.valueOf(randNum);
session.setAttribute("randStr",randStr);
g.setColor(Color.black);
g.setFont(new Font("",Font.PLAIN,20));
g.drawString(randStr,10,17);
//随机产生一百个使图像中的验证码不容易被其他程序识别到
for(int i=0;i<100;i++){
int x=rnd.nextInt(width);
int y=rnd.nextInt(height);
g.drawOval(x,y,1,1);
}
//输出到图像页面中
ImageIO.write(image,"JPEG",response.getOutputStream());
//ImageIO.write(image, "jpg", new File("F:/test.jpg")); 保存到本地
out.clear();
out=pageContext.pushBody();
%>
<body>
</body>
</html>