out.println("验证码<input type='text' name='checkcode'/>
<img src='/Servlet4/CreateCode'/><br />");
src='/project name/ class name'
public class CreateCode extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. Disable browser caching of random images response.setDateHeader("Expires", - 1); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); //2. Notify the client to open the sent data response as a picture .setHeader("Content-Type", "image/jpep"); //1. Create a picture in memory BufferedImage image=new BufferedImage(80,30,BufferedImage.TYPE_INT_BGR); //2. Write data up Graphics g=image.getGraphics(); //Set the background color g.setColor(Color.BLACK);
g.fillRect(0,0,80,30);
//3. Set the color and font of the written data
g.setColor(Color.WHITE);
g.setFont(new Font(null,Font.BOLD,20)) ;//???
// 4. Write data to the picture
String num=makeNum();
//This sentence is a randomly generated value, which is saved to session
request.getSession().setAttribute("checkcode", num );
g.drawString(num, 0, 20);
//3. Output the written data image to the browser
ImageIO.write(image, "jpg",response.getOutputStream());
}
//4. The Randomly generate 7 digits when the function is used
public String makeNum(){
Random r=new Random();
String num =r.nextInt(9999999)+"";
StringBuffer sb=new StringBuffer();
for(int i=0;i <7-num.length();i++){
sb.append("0");
}
num=sb.toString()+num;
return num;
}