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 .*;
Public class ValidateCode 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 + "";
// Save the input session for comparison with the user input.
// Clear the session after comparison.
HttpSession session = request. getSession (true );
Session. setAttribute ("validateCode", 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 ();
}
}
The image processing package of java requires a graphical environment, but the graphic environment is not started on linux. Therefore, this error is reported because the server (X11 window server using ': 100') in the graphic environment cannot be found. By specifying the java-Djava. awt. headless = true parameter, you can avoid finding a graphical environment in java 2d.
You can either try it like this. In the servlet, write the following statement at the beginning:
System. setProperty ("java. awt. headless", "true ");
Java. awt. headless = true
Take tomcat (a very useful JSP running platform) as an example.
You can add:
CATALINA_OPTS = "...-Djava. awt. headless = true"
Others can also look at the startup script. You can add this parameter.