package com.hull.validatecode;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.sun.image.codec.jpeg.*;
public class ValidateCode extends HttpServlet
{
private Font imgFont = new Font("宋体",Font.BOLD,16); //设置字体
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
doPost(request,response);
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
String vCode = "";
int intCode = 0;
intCode = (new Random()).nextInt(9999);
if(intCode<1000)
intCode += 1000;
vCode = intCode+"";
/*
* 绘图
*/
response.setContentType("image/gif");
ServletOutputStream vout = response.getOutputStream();
BufferedImage image = new BufferedImage(50,20,BufferedImage.TYPE_INT_RGB);
Graphics graph = image.getGraphics();
// 设置背景颜色
graph.setColor(Color.white);
graph.fillRect(1,1,48,18);
//设置字体颜色
graph.setColor(Color.black);
graph.setFont(imgFont);
char c;
for(int i=0;i<4;i++)
{
c = vCode.charAt(i);
graph.drawString(c+"",9*i+4,16);
}
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(vout);
encoder.encode(image);
// 对session赋值
HttpSession session = request.getSession(true);
session.removeAttribute("VerifyCode");
session.setAttribute("VerifyCode",vCode);
vout.close();
}
}
调用:
<img src="ValidateCode" align="center">