Call Method
In servlet, a 4-digit 1000-9999 is randomly generated.
Then write the number to the session.
Output an image containing the four numbers
The number and
Compare the values in the 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 generates a 4-digit verification code at random and writes it to 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 {
// Obtain a random number of 1000-9999
String s = "";
Int intCount = 0;
IntCount = (new Random (). nextInt (9999 );//
If (intCount <1000) intCount + = 1000;
S = intCount + "";
// Pay for 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 );
Graphics gra = image. getGraphics ();
// Set the background color
Gra. setColor (Color. yellow );
Gra. fillRect );
// Set the font color
Gra. setColor (Color. black );
Gra. setFont (mFont );
// Output number
Char c;
For (int I = 0; I <4; I ++ ){
C = s. charAt (I );
Gra. drawString (c + "", I * 7 + 4, 11); // 7 indicates the width, and 11 indicates the upper and lower heights.
}
Required imageencoder encoder = required codec. createJPEGEncoder (out );
Encoder. encode (image );
Out. close ();
}
}