I am trying to build a simple java servlet that runs in tomcat server on my machine.
My servlet code is :
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class javaservlet
*/
#WebServlet(description = "java servlet", urlPatterns = { "/javaservlet" })
public class javaservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public javaservlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter writer = response.getWriter();
calldll callingdll = new calldll();
ServletContext context = getServletConfig().getServletContext();
String path = context.getContextPath();
writer.println(path);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
and it works fine (not of the calldll callingdll = new calldll(); part i will explain below what error i get there)
I also have a second class that loads the dll file called "calldll.dll" (did all the work with javac , javah and stuff and it works ) my dll is placed in C:\apache-tomcat-7.0.37\wtpwebapps\myServlet\WEB-INF\lib and i have pointed build path of native there and my class code is
public class calldll {
private native void print();
public static void main (String[] args){
new calldll().print();
}
static {
System.loadLibrary("calldll");
}
}
My c file where i made the dll from is a really simple
#include<jni.h>
#include<stdio.h>
#include<windows.h>
#include "calldll.h"
JNIEXPORT void JNICALL
Java_calldll_print(JNIEnv*env,jobject obj)
{
printf("It Works!");
return;
}
when i run the javaservlet where i call the call dll class that loads the dll i get this :
java.lang.NoClassDefFoundError: Could not initialize class calldll
javaservlet.doGet(javaservlet.java:33)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
The weird thing is that when i run the java class alone the message "It works" comes up so the class loads the dll successfully. But when when i create an instance of the class in the servlet it doesnt it from the servlet is doesn't that is my problem....
i added to the calldll class
catch(UnsatisfiedLinkError e)
{
System.err.println("Native code library failed to load.\n" + e);
}
to see if it is a problem with static and i get the following error when i run the servlet
Native code library failed to load.
java.lang.UnsatisfiedLinkError: no calldll in java.library.path
but my calldll class if i execute it alone it still works... so what is happening in the servlet that i do wrong :s
If your webapp is hosted in tomcat app server copy the dll to bin folder, then in your servlet use :
System.load(System.getProperty("catalina.base")+"/bin/yourdll.dll");
Related
So I had an Eclipse project given to me, which I opened in Eclipse and converted to a web project and began writing a servlet + JSP pages for it. It was working fine, until this morning when I cleaned the project using Eclipse's in-built clean function.
Now I am getting the 404 with 'Requested resource is not available' where it was working fine before.
Here is the Servlet code:
package servlets;
import is2.data.SentenceData09;
import is2.lemmatizer.Lemmatizer;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class FYPServlet
*/
#WebServlet("/FYPServlet")
public class FYPServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public FYPServlet() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("sentence")!=null){
//Create container
SentenceData09 sentence = new SentenceData09();
//Split input up
String[] words = request.getParameter("sentence").split(" ");
String lastword = words[words.length-1];
int sizeoflastword = lastword.length();
//If sentence has a full stop, remove it
if(lastword.charAt(sizeoflastword-1)=='.'){
words[words.length-1] = lastword.substring(0,sizeoflastword-1);
}
//Add <root> to start and a full stop to end
String[] fullsentencewords = new String[words.length+2];
fullsentencewords[0] = "<root>";
int i=1;
for(String word : words){
fullsentencewords[i] = word;
i++;
}
fullsentencewords[fullsentencewords.length-1] = ".";
//Initialise the container
sentence.init(fullsentencewords);
//Give lemmatizer location of model
is2.lemmatizer.Options optsLemmatizer = new is2.lemmatizer.Options(new String[] {"-model","C:/Users/Illuria/Downloads/small-models-english/small-models-english/models/lemmatizer-eng-4M-v36.mdl"});
//Create lemmatizer
Lemmatizer lemmatizer = new Lemmatizer(optsLemmatizer);
//Apply the lemmatizer
lemmatizer.apply(sentence);
//Display the lemmata
for (String l : sentence.plemmas) System.out.println("lemma : "+l); //TODO: Push this to the new page
request.setAttribute("lemmas", sentence.plemmas);
request.getRequestDispatcher("ParseDisplay.jsp").forward(request, response);
}else{
response.sendRedirect("EntryForm.jsp");
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
The exact 404 I am getting is:
HTTP Status 404 - /mate-tools-2/FYPServlet
type: Status report
message: /mate-tools-2/FYPServlet
description: The requested resource is not available
Unfortunately I'm a bit of a newbie at web development so any help would be greatly appreciated!
Not sure if you are still having trouble but sometimes just cleaning wont help. I remove webapp from Tomcat eclipse (right click on Tomcat and do 'Add or Remove'), clean it and add it back. Let us know if this helps.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I want to create a report in pdf format by using servlet, .jasper file,but there is a exception:
HTTP Status 500 - Servlet execution threw an exception
--------------------------------------------------------------------------------
type Exception report
message Servlet execution threw an exception
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet execution threw an exception
root cause
java.lang.NoClassDefFoundError:
net/sf/jasperreports/engine/JasperRunManager
one.Patient.doGet(Patient.java:46)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
note The full stack trace of the root cause is available in the Apache
Tomcat/7.0.34 logs.
servlet code is:
package one;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.util.HashMap;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperRunManager;
/**
* Servlet implementation class Patient
*/
#WebServlet("/Patient")
public class Patient extends HttpServlet implements Servlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Patient() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Connection con=DBCon.getConnection();
InputStream inS=getServletContext().getResourceAsStream("/report-src/ganeshaji.jashper");
OutputStream outS=response.getOutputStream();
response.setContentType("application/pdf");
try {
JasperRunManager.runReportToPdfStream(inS, outS, new HashMap<String, Object>(),con);
outS.flush();
con.close();
} catch (Exception e) {
// TODO Auto-generated catch block
response.setContentType("text/html");
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
pls. provide me solution
By looking into the root Cause
java.lang.NoClassDefFoundError: net/sf/jasperreports/engine/JasperRunManager
it seems like you either miss the jasper jar or have the wrong version which doesn't support JasperRunManager.
Including the proper jar in the class path will solve your issue.
Please download these jars:
itext-4.2.0.jar
itextpdf-5.3.4.jar
jasperreports-4.0.1.jar
jasperreports-fonts-4.0.0.jar
and code something like:
try {
FileInputStream fis = new FileInputStream(YOURREPORTPATH.jasper");
BufferedInputStream bufferedInputStream = new BufferedInputStream(fis);
jasperReport = (JasperReport) JRLoader.loadObject(bufferedInputStream);
} catch (Exception e2) {
e2.printStackTrace();
}
and then after filling the parameters and the datasource create pdf like this:
JasperExportManager.exportReportToPdfFile(jasperPrint, OUTPUTFILENAME+".pdf");
Thanks...
Mr.777
detected the root Exception, which was thrown before NoClassDefFoundError:net/sf/jasperreports/engine/util/JRStyledTextParser :
java.lang.NoClassDefFoundError: sun/awt/X11GraphicsEnvironment
The Sun AWT classes on Unix and Linux have a dependence on the X Window System. When you use these classes, they expect to load X client libraries and be able to talk to an X display server. This makes sense if your client has a GUI; unfortunately, it's required even if your client uses AWT but does not have a GUI (which is my case, generating a report from a web application)
The way to bypass this, is setting a system property java.awt.headless=true on system startup.
For Example
Let java execute the static block as early as possible by moving it to the top of the class!
public class Foo() {
static { /* works fine! ! */
System.setProperty("java.awt.headless", "true");
}
public static void main() {}
}
or
I think this parameter can be set by passing it as an argument to Java Virtual Machine e.g.
-Djava.awt.headless=true. Not sure if this would have impact on other components of your application.
or
Try putting this in your ${CATALINA_HOME}/bin/catalina.sh script:
export JAVA_OPTS="${JAVA_OPTS} -Djava.awt.headless=true"
refered from-https://stackoverflow.com/a/3651196/1602230
So my next problem with this code. It seemse to not be finding a method and my eyes are untrained. Any help available on this?
package packeging;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.amazonaws.HttpMethod;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.auth.BasicAWSCredentials;
import org.apache.http.*;
/**
* Servlet implementation class Hashtastic
*/
#WebServlet("/Hashtastic")
public class Hashtastic extends HttpServlet {
private static final long serialVersionUID = 1L;
private final static String BUCKET_NAME = "idlatestingbucket";//http://s3.amazonaws.com/THESISDB/techy.jpg
private final static String FILE_NAME = "TestPicture/wallpaper-264411.png";
private final static String ACCESS_KEY = "Fakepass";
private final static String SECRET_KEY = "Fakekey";
/**
* Default constructor.
*/
public Hashtastic() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 1000);
Date expDate = cal.getTime();
out.println(expDate+"\n");
BasicAWSCredentials cre = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
AmazonS3 s3 = new AmazonS3Client(cre);
String url = s3.generatePresignedUrl(BUCKET_NAME, FILE_NAME, expDate, HttpMethod.GET).toString();
out.println(url);
out.close();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
I am getting this 500 error. It says that it is missing a method. I have the jar in my lib and plugins for eclipse.
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet execution threw an exception
root cause
java.lang.NoSuchMethodError: org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager: method <init>()V not found
com.amazonaws.http.ConnectionManagerFactory.createThreadSafeClientConnManager(ConnectionManagerFactory.java:26)
com.amazonaws.http.HttpClientFactory.createHttpClient(HttpClientFactory.java:83)
com.amazonaws.http.AmazonHttpClient.<init>(AmazonHttpClient.java:116)
com.amazonaws.AmazonWebServiceClient.<init>(AmazonWebServiceClient.java:60)
com.amazonaws.services.s3.AmazonS3Client.<init>(AmazonS3Client.java:291)
com.amazonaws.services.s3.AmazonS3Client.<init>(AmazonS3Client.java:273)
packeging.Hashtastic.doGet(Hashtastic.java:48)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.27 logs.
This could happen if you have the wrong version of the httpclient jar in your classpath, or if you have more than one version of that jar in your classpath (e.g. having both httpclient-4.0.1.jar and httpclient-4.1.1.jar).
It could also be caused by another jar containing a different version of the same class. For example, I know that gwt-dev.jar contains a version of ThreadSafeClientConnManager. If this is the case, the problem could probably be solved by adjusting the build path order to put httpclient.jar before gwt-dev.jar (or the other jar causing problem).
From experience with this exact same Exception, the chances are fairly good that it is caused by gwt-dev appearing before aws-java-sdk in your classpath and due to gwt-dev containing a conflicting (in terms of classloading) version of org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager
If you happen to be using Maven, re-order your dependencies as follows and perhaps add a warning to fellow maintainers on the significance of the ordering.
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.3.26</version>
</dependency>
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-dev</artifactId>
<version>2.3.0</version>
</dependency>
I need to programmatically add and remove a servlet on a Jetty 6 server.
While it is almost straighforward to add I cannot find an effective way to remove.
For my purposes it is important to add and remove a servlet because it is associated to a dynamic compontent architecture. I need to add a new service when I add a component and I need to remove the service when I remove the component.
To add a servlet I used this pattern:
Server server = new Server(8080);
class MyServlet extends HttpServlet
{
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
resp.getOutputStream().write("Hello World!".getBytes());
}
}
...
public void addServlet(HttpServlet s, String path)
{
Context root = new Context(server,"/",Context.SESSIONS);
root.addServlet(new ServletHolder(new MyServlet()), "/test/*");
root.getServletHandler().
}
public void removeServlet(HttpServlet s, String path)
{
//What I have to put here ? There is no removeServlet like methods in server/Context/ServletHolder
}
Why removing a servlet is not so obvious? Can you explain me the motivations ?
first off I would recommend updating to jetty 7 or 8 if its possible, jetty 6 is quite old at this point and is lacking the last couple years of development that are present in 7 and 8. heck, jetty 9 is being actively worked on now.
second I wouldn't look at this on the servlet level but the handler level, working with the server to add and remove handlers, which can be either static resource type handlers or full fledged servlet context handlers, or even webapp context handlers.
as to why the servlet context handlers do not have remove servlet type operations, its really not a part of the servlet spec to remove active servlets at that level, fits more at the war deploy/undeploy level. feel free to open an issue on it though, I did experiment with adding and removing at servlet context handler level and you can remove them but it seems to be problematic then adding more afterwards, so I suspect removing the context itself and adding a new one would be your best bet at this point.
Here's instructions for doing it on Jetty 7.
Jetty : Dynamically removing the registered servlet
It should be pretty straight forward to port that code to Jetty 6.
This solution seems to be working:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.ContextHandler;
import org.mortbay.jetty.handler.ContextHandlerCollection;
import org.mortbay.jetty.handler.ResourceHandler;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHandler;
import org.mortbay.jetty.servlet.ServletHolder;
import org.mortbay.jetty.servlet.ServletMapping;
public class MyServer extends Server
{
ServletHandler sh = new ServletHandler();
public MyServer()
{
super(9090);
setHandler(sh);
test();
}
class MyServlet extends HttpServlet
{
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
resp.getWriter().println("CIAO!");
}
}
void test()
{
MyServlet ms = new MyServlet();
addServlet(ms, "/ciao/*");
//removeServlet(ms);//uncomment this ilne in order to remove the servlet right after the deploy
}
public void addServlet(HttpServlet s, String path)
{
sh.addServletWithMapping(new ServletHolder(s), path);
for (ServletHolder so : sh.getServlets())
try
{
System.out.println((so.getServlet() == s));
} catch (ServletException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void removeServlet(HttpServlet s)
{
try
{
HashSet<String> names = new HashSet<String>();
for (ServletHolder so : sh.getServlets())
if (so.getServlet() == s)
names.add(so.getName());
HashSet<ServletMapping> sms = new HashSet<ServletMapping>();
for (ServletMapping sm : sh.getServletMappings())
{
if (!names.contains(sm.getServletName()))
sms.add(sm);
}
sh.setServletMappings(sms.toArray(new ServletMapping[] {}));
} catch (ServletException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I have a scenario where I need to display charts(generated using jfreecharts) converted it into a png image and then display them using servlets.
When the chart code extends either ApplicationFrame or Jframe I see the following exception when I display it using servlets :
java.awt.HeadlessException:
No X11 DISPLAY variable was set, but this program performed an operation which requires it.
at java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:159)
at java.awt.Window.(Window.java:317)
at java.awt.Frame.(Frame.java:419)
at javax.swing.JFrame.(JFrame.java:194)
I read through a couple of places and this seems to be because of the ApplicationFrame and JFrame would cause this error.
If i pass just the chart object this throws a
java.lang.IllegalArgumentException: Null 'chart' argument.
org.jfree.chart.ChartUtilities.writeChartAsPNG(ChartUtilities.java:181)
org.jfree.chart.ChartUtilities.writeChartAsPNG(ChartUtilities.java:136)
Is there any solution for this?
ChartUtilities is the right choice; streams are supported, too. One approach requires Using Headless Mode in the Java SE Platform, but I've also gotten it to work with VNC.
Addendum: here's a related forum thread.
I will explain you in simple way as I faced the same problem as i was new.
Steps
Create a servlet
In doPost create outputstream
set content type to text/png
Create datasets
set values to dataset
create instance of jfreechart and call createchart(the chart you wanna use) using ChartFqactory.
finally call WriteChartAsPNG using ChartUtilities and pass the Jfreechart instance,outputstream,width,height.
DONE:
Sample below
package polo;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
/**
* Servlet implementation class PieChartDemo1Serv
*/
public class PieServ extends HttpServlet implements useme {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public PieServ() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("image/png");
ServletOutputStream out = response.getOutputStream();
DefaultPieDataset pieDataset = new DefaultPieDataset();
pieDataset.setValue("In-Network ", .80);
pieDataset.setValue("Out-of-Network ", .20);
JFreeChart chart = ChartFactory.createPieChart("", pieDataset, true, true, false);
ChartUtilities.writeChartAsPNG(out, chart, 202, 182);
System.out.println("done23");
}
}
Now I know you what further.Study Pieplots/Legends to setup border and formatting.You can do a lot further.