js| Graphics | Verification Code
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 ("Arial", font.plain,12);//Set 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 of 1000-9999
String s= "";
int intcount=0;
Intcount= (New Random ()). Nextint (9999);
if (intcount<1000) intcount+=1000;
S=intcount+ "";
Save in session for comparison with user input.
Note that the session is cleared after the comparison is complete.
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 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 width, 11 is the top and bottom height position
}
JPEGImageEncoder Encoder=jpegcodec.createjpegencoder (out);
Encoder.encode (image);
Out.close ();
}
}
Java Image processing package requires a graphics environment, and Linux does not start the graphics environment, the graphics environment can not find the server (X11 window server using ': 0.0 ') so will report this error. By java-djava.awt.headless=true This parameter's designation can avoid Java 2d to find graphics environment.
Either try it or you can. At the beginning of the servlet, write a sentence:
System.setproperty ("Java.awt.headless", "true");
The Java Virtual machine for the Web server must be a parameter java.awt.headless=true
Taking Tomcat as an example
You can add in the catalina_opts variable in the. Bash_profile of the user who/etc/profile or starts the Web service:
Catalina_opts= "...-djava.awt.headless=true"
Others can also look at the startup script. Just add this parameter to the problem.