views:

46

answers:

3

I want to run the servlet in elipse. For this I have created a dynamic web project and I have deployed my servlet.java file under WEB-INF folder. I have also added servlet.jar file. How can I run the file as a java application?

A: 

Servlets cannot be run directly as an Java app. I recommend two approaches:

  1. Refactor your servlet and put your "java" code (what ever generic code you want to call) in another jar that you call from both the servlet and the Java application.

  2. Run the servlet in a container in Eclipse. See http://www.eclipse.org/jetty/ Communicate with the servlet through HttpRequest's and HttpResponse's

+1  A: 

Servlets run in servlet/JSP engines, like Tomcat or Resin or Jetty. You normally don't run them outside a container.

You can certainly deploy your app to a servlet/JSP engine and start in from Eclipse. But it's the app server that you run, which then acts as the home for your servlet.

duffymo
A: 

Servlets run in a servletcontainer. Servlets are not "plain vanilla" java applications. See, they do not have a main() method! Servlets listens on HTTP requests and returns HTTP responses through the network. Running the sole servlet class as a plain vanilla Java application doesn't automagically make them to listen and react on HTTP requests.

Apache Tomcat is a popular servletcontainer. Just download and unzip it. Then in Eclipse (I assume that you already have downloaded the Eclipse Java EE version, else drop it all together and redownload the right version), go to Servers view and add the newly installed Tomcat instance. Then create a Dynamic Web Project wherein you pick the newly integrated server instance from the list. Eclipse will then automatically take the Servlet API libraries in the classpath/buildpath (thus, you do NOT need to download a random "servlet.jar file" separately yourself! this is only receipt for major trouble). Then create a Servlet class and register it in web.xml. Then deploy the project to the newly integrated server and start it. Then in your favourite webbrowser go to http://hostname:port/contextname which is usually http://localhost:8080/webprojectname.

To learn more about servlets (and Eclipse and Tomcat) I strongly recommend you to go through those tutorials. You can also search on youtube for video tutorials using the obvious keywords.

BalusC