|
![]() |
名片设计 CorelDRAW Illustrator AuotoCAD Painter 其他软件 Photoshop Fireworks Flash |
|
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为例 可以在/etc/profile或启动web服务的用户的.bash_profile中的CATALINA_OPTS变量中加入: CATALINA_OPTS="... -Djava.awt.headless=true" 其他的也可以看看启动脚本。只要加上这个参数就没问题了。 返回类别: 教程 上一教程: 使用JAVA实现网络传输数据的压缩 下一教程: 不建议在JSP页面中直接写语句连接数据库 您可以阅读与"用JSP实现图形验证码"相关的教程: · 产生彩色验证码_(JAVABEAN实现) · JSP中图片验证的实现 · JSP生成验证码源程序 · JSP生成彩色验证码程序 · 产生彩色验证码_(javabean实现) |
![]() ![]() |
快精灵印艺坊 版权所有 |
首页![]() ![]() ![]() ![]() ![]() ![]() ![]() |