这是servlet的代码
package web;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class CheckcodeServlet extends HttpServlet {
private int WIDTH= 80;
private int HEIGHT= 30;
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//一、绘图
//step1,创建一个内存映像对象(画布)
BufferedImage image =
new BufferedImage(WIDTH,HEIGHT,
BufferedImage.TYPE_INT_RGB);
//step2,获得画笔
Graphics g = image.getGraphics();
//step3,
Random r = new Random();
//step3,给画笔上一个随机的颜色
g.setColor(new Color(r.nextInt(255),
r.nextInt(255),r.nextInt(255)));
//step4,填充画布
g.fillRect(0, 0, WIDTH, HEIGHT);
//step5,在画布上绘图
// String number = r.nextInt(99999) + "";
String number ="";
// g.setColor(new Color(0,0,0));
for (int i = 0; i < 4; i++) {
g.setColor(new Color(r.nextInt(255),
r.nextInt(255),r.nextInt(255)));
int h=(int)(HEIGHT*0.3+(HEIGHT*0.7)*r.nextDouble());
g.setFont(new Font(null,Font.ITALIC|Font.BOLD,h));
String str=getNumber(1);
number+=str;
g.drawString(str, i*WIDTH/5, h);
}
//将number 绑定到session上
HttpSession session =request.getSession();
session.setAttribute("number", number);
//step6,设置字体的大小、风格
// g.setFont(new Font(null,
// Font.ITALIC|Font.BOLD,20));
// g.drawString(number, 5, 22);
//加干扰线
for (int i = 0; i < 3; i++) {
g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255),r.nextInt(255)));
g.drawLine(r.nextInt(WIDTH), r.nextInt(HEIGHT),r.nextInt(WIDTH), r.nextInt(HEIGHT));
}
//二、压缩图片,输出
response.setContentType("image/jpeg");
OutputStream ops =
response.getOutputStream();
//write方法:将原始图片(image)使用
//指定的压缩算法(jpeg)进行压缩,然后
//使用指定的输出流(ops)输出。
ImageIO.write(image, "jpeg", ops);
ops.close();
}/*返回一个指定长度的字符串
要求从A~Z,0~9中随机选取字符
*/
private String getNumber(int size) {
Random r=new Random();
String strs="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+"0123456789";
String number="";
for (int i = 0; i < size; i++) {
number+=strs.charAt(r.nextInt(strs.length()));
}
return number;
}
}
jsp中代码
<h3>验证码:<h3/>
<img id="num" src="CheckcodeServlet" />
<a href="javascript:;" onclick="document.getElementById('num').src = 'CheckcodeServlet?'+Math.random()">换一张</a>
------解决思路----------------------
订!!!!!!!!!!
------解决思路----------------------
路径对不。看看后台请求到了没?