class="java" name="code"> 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; import javax.servlet.http.HttpSession; public class ChineseCheckCode extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); response.setContentType("image/jpeg"); response.setDateHeader("expries", -1); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); int width=166; int height = 80; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Graphics g=image.getGraphics(); Random randome = new Random(); Font myFont = new Font("宋体",Font.ITALIC,26); g.fillRect(0, 0, width, height); g.setFont(myFont); String sRand = ""; String ctmp = ""; String itmp = ""; for(int i=0;i<4;i++){ String[] rBase={"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"}; int r1=randome.nextInt(3)+11; String str_r1=rBase[r1]; int r2; if(r1==13){ r2=randome.nextInt(7); }else{ r2=randome.nextInt(16); } String str_r2=rBase[r2]; int r3=randome.nextInt(6)+10; String str_r3=rBase[r3]; int r4; if(r3==10){ r4=randome.nextInt(15)+1; }else if(r3==15){ r4=randome.nextInt(15); }else{ r4=randome.nextInt(16); } String str_r4=rBase[r4]; byte[] bytes = new byte[2]; String r12=str_r1+str_r2; int tempLow=Integer.parseInt(r12, 16); bytes[0]=(byte) tempLow; String r34=str_r3+str_r4; int tempHeigh=Integer.parseInt(r34, 16); bytes[1]=(byte) tempHeigh; ctmp=new String(bytes); sRand+=ctmp; Color color = new Color(20+randome.nextInt(110)); g.setColor(color); g.drawString(ctmp, width/6*i+23, height/3); } HttpSession session=request.getSession(true); session.setAttribute("randCheckCode", sRand); g.dispose(); ImageIO.write(image, "JPEG", response.getOutputStream()); } }