问题
I am using the following code in a servlet of my app
java.awt.Image awtImg = java.awt.Toolkit.getDefaultToolkit().createImage(str1);
When I run the application and call the servlet I get the following error
java.lang.NoClassDefFoundError: Could not initialize class sun.awt.X11.XToolkit
java.lang.Class.forName0(Native Method)
java.lang.Class.forName(Class.java:169)
java.awt.Toolkit$2.run(Toolkit.java:834)
java.security.AccessController.doPrivileged(Native Method)
java.awt.Toolkit.getDefaultToolkit(Toolkit.java:826)
noticeandreports.pdf.appendFiles.PdfFunctionsClass.addSealSpace(PdfFunctionsClass.java:198)
OJ.NoticesandReports.generate_151_OJNotice.execute(generate_151_OJNotice.java:768)
org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
I have hosted the app on a Linux machine with Java version JDK 1.6.20..
What might be causing the issue...
noticeandreports.pdf.appendFiles.PdfFunctionsClass
is the class where the code is written and OJ.NoticesandReports.generate_151_OJNotice
is the servlet that calls the method inside the above class...
回答1:
To use AWT classes in a server side application, I believe you need to run in "headless" mode. Change your servlet container's startup to include:
-Djava.awt.headless=true
(Or set the system property within your own code if you really have to.)
You might also want to consider using an alternative imaging library - either a third-party one or the javax.imageio
package.
回答2:
That is almost certainly not the complete stack trace. Either that stack trace or an earlier one in the log file will tell you what caused the initialization of sun.awt.X11.XToolkit
to fail.
However, I'd hazard a guess that the root cause is that the JVM running the web countainer is "headless"; i.e. it doesn't have an accessible display.
The Oracle Java Technical Article entitled "Using Headless Mode in the Java SE Platform" (by Artem Ananiev and Alla Redko, June 2006) describes the issue and what to do about it.
The solution is probably as simple as adding -Djava.awt.headless=true
to the JVM options in the web container startup script. For instance, if you are using Tomcat, add that to the $JAVA_OPTS
environment variable before calling catalina.sh
.
来源:https://stackoverflow.com/questions/5576986/servlet-giving-error-java-lang-noclassdeffounderror