
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);//配置字体 //处理post public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
doGet(request,response); } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { //取得一个1000-9999的随机数 String s="";
int intCount=0;
intCount=(new Random()).nextInt(9999);//
if(intCount<1000)intCount+=1000;
s=intCount+"";
//保存入session,用于和用户的输入进行比较. //注意比较完之后清除session.
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(); //配置背景色 gra.setColor(Color.yellow);
gra.fillRect(1,1,33,12); //配置字体色 gra.setColor(Color.black);
gra.setFont(mFont); //输出数字 char c;
for(int i=0;i<4;i++) {
c=s.charAt(i);
gra.drawString(c+"",i*7+4,11); //7为宽度,11为上下高度位置
}
JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();
} }
java的图片处理包需要图像环境,而linux上没有启动图像环境,很难找到图像环境的server(X11 window server using ’:0.0’ )所以会报这个错。而通过java -Djava.awt.headless=true 这个参数的指定就能够避免java 2d去找图像环境。
要么这样试试,应该也能够。在servlet里一开始写一句:
System.setProperty("java.awt.headless","true");
web服务器的java虚拟机必须加以个参数java.awt.headless=true
以tomcat(一个很好用的JSP运行平台)为例
能够在/etc/profile或启动web服务的用户的.bash_profile中的CATALINA_OPTS变量中加入:
CATALINA_OPTS="... -Djava.awt.headless=true"
其他的也能够看看启动脚本。只要加上这个参数就没问题了。
|