package com.wsx;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
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;
public class CreateCode extends HttpServlet {
/**
* Constructor of the object.
*/
public CreateCode() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html ;charset=utf-8");
//防止浏览器缓存随机图片
response.setDateHeader("Expires", -1);
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragna", "no-cache");
//通知客户机以图片方式打开发送过去的数据
response.setHeader("Content-Type", "image/jpeg");
//1、在内存中创建一副图片
BufferedImage image=new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB);
//2、向图片上写数据
Graphics g=image.getGraphics();//获得画笔
//设置背景色
g.setColor(Color.WHITE);
g.fillRect(0, 0, 80,30);//矩形框
//3、设置写入数据的颜色和字体
g.setColor(Color.BLACK);
g.setFont(new Font(null,Font.BOLD,20));
//4、向图片上写数据
String num=makeNum();
request.getSession().setAttribute("checkcode", num);
g.drawString(num, 0,20);
//把写好的数据的图片输出给浏览器
ImageIO.write(image, "jpg", response.getOutputStream());
//该函数用于生成7位数字
}
public String makeNum() {
Random r=new Random();
//999999用来产生7位数,因此你可以修改999999来生成你要的验证码位数
String num=r.nextInt(9999999)+"";
StringBuffer sb=new StringBuffer();
//如果不够7位前面补0
for(int i=0;i<7-num.length();i++){
sb.append("0");
}
num=sb.toString()+num;
return num;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
使用方法:
<img src='验证码的url'> out.println("验证码:<input type='text' name='checkcode'/><img src='/mycheckcode/CreateCode'/><br/>");