Username: Password:

JSP图像验证码的系统配置
来源:WEB开发者 作者:未知  发布时间:2008-03-03 10:30:37

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"

  其他的也能够看看启动脚本。只要加上这个参数就没问题了。

喜欢本文,那就收藏到:

    Del.icio.us Google书签 Digg Live Bookmark Technorati Furl Yahoo书签 Facebook 百度搜藏 新浪ViVi 365Key网摘 天极网摘 和讯网摘 博拉网 POCO网摘 添加到饭否 QQ书签 Digbuzz我挖网
相关评论  我也要评论
还没有关于此文章的相关评论!
  • 昵称: (为空则显示guest)
  • 评论分数: ★ ★ ★★★ ★★★★ ★★★★★
  • 评论内容:(不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
  • 导航
    赞助商
    文章类别
    订阅