jsp驗證碼無法顯示

把開發好的代碼,放到Linux服務器上面,有的Linux服務器可以顯示,有的沒有顯示。

經過對比,發現該問題更深一步是這樣:


1 如果以init 5的級別啓動centos系統,再啓動tomcat,在客戶端瀏覽器上查看驗證碼圖形顯示正常;


2 如果以init 3的級別啓動centos系統,再啓動tomcat,在客戶端瀏覽器上查看驗證碼圖形顯示顯示爲小紅叉;


這是很重要的結論,這個錯誤是因爲圖表程序是通過AWT實現的,AWT會調用操作系統本地窗口資源繪圖,windows對此支持很好,

在linux下如果沒有進到X window,AWT就不能繪圖。

代碼如下


<%@ page contentType="image/jpeg" import="java.awt.*,
java.awt.image.*,java.util.*,javax.imageio.*" pageEncoding="GB18030"%>
<%@ page import="java.io.OutputStream" %>
<%!
Color getRandColor(int fc,int bc){//給定範圍獲得隨機顏色
        Random random = new Random();
        if(fc>255) fc=255;
        if(bc>255) bc=255;
        int r=fc+random.nextInt(bc-fc);
        int g=fc+random.nextInt(bc-fc);
        int b=fc+random.nextInt(bc-fc);
        return new Color(r,g,b);
        }
%>
<%
//設置頁面不緩存
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);

// 在內存中創建圖象
int width=48, height=14;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

// 獲取圖形上下文
Graphics g = image.getGraphics();

//獲取輸出流:
OutputStream os=response.getOutputStream();

……………………………………………………
%>

執行到這一行的時候報錯Graphics g = image.getGraphics();

報的錯誤如下:

有的服務器出現的是,Error   請聯繫系統管理員

有的服務器是報下面的錯誤:

org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.NoClassDefFoundError: Could not initialize class sun.awt.X11GraphicsEnvironment
javax.servlet.ServletException: java.lang.NoClassDefFoundError: Could not initialize class sun.awt.X11GraphicsEnvironment
java.lang.NoClassDefFoundError: Could not initialize class sun.awt.X11GraphicsEnvironment

第一種方法加入:-Djava.awt.headless=true ,沒有解決

在catalina.sh中,450行左右加入

-Djava.awt.headless=true \

加了之後是報別的錯誤

 

org.apache.jasper.JasperException: javax.servlet.ServletException: java.awt.AWTError: Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable.
javax.servlet.ServletException: java.awt.AWTError: Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable.
java.awt.AWTError: Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable.

 

第二種方法:在catalina.sh文件裏面加入,可以順利解決

export CATALINA_OPTS="-Djava.awt.headless=true"

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章