jsp implements graphic verification code
Author:Eve Cole
Update Time:2009-07-02 17:08:30
call method
<img src=" http://...../getImg ">
The principle is to randomly generate a 4-digit number 1000-9999 in the servlet
Then write this number into the session
Output a picture with these four numbers written on it
On the server side, based on the number entered by the user and
Value comparison in session.
package com.schoolwx.util;
import java.io.*;
import java.util.*;
import com.sun.image.codec.jpeg.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.awt.*;
import java.awt.image.*;
/**
* Title: getImg.java
* Description: This class mainly implements randomly generating a 4-digit verification code and writing it into the session.
* Copyright: Copyright (c) 2003
* Company: Blue Star Software
* @author falcon
* @version 1.1
*/
public class getImg extends HttpServlet {
private Font mFont=new Font("宋体", Font.PLAIN,12);//Set the font
//process post
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
doGet(request,response);
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
//Get a random number from 1000-9999
String s="";
int intCount=0;
intCount=(new Random()).nextInt(9999);//
if(intCount<1000)intCount+=1000;
s=intCount+"";
//Pay value to the session.
HttpSession session=request.getSession (true);
session.setAttribute("getImg",s);
response.setContentType("image/gif");
ServletOutputStream out=response.getOutputStream();
BufferedImage image=new BufferedImage(35,14,BufferedImage.TYPE_INT_RGB);
Graphicsgra=image.getGraphics();
//Set background color
gra.setColor(Color.yellow);
gra.fillRect(1,1,33,12);
//Set font color
gra.setColor(Color.black);
gra.setFont(mFont);
//Output numbers
char c;
for(int i=0;i<4;i++) {
c=s.charAt(i);
gra.drawString(c+"",i*7+4,11); //7 is the width, 11 is the top and bottom height positions
}
JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();
}
}
http://blog.csdn.net/lixiaolong_blog/archive/2007/01/25/1493417.aspx