开发者

how to run the servlet in eclipse?

开发者 https://www.devze.com 2022-12-21 08:38 出处:网络
I want to run a servlet in Eclipse. For this I have cr开发者_StackOverflow社区eated a dynamic web project and I have deployed my servlet.java file under the WEB-INF folder. I have also added the servl

I want to run a servlet in Eclipse. For this I have cr开发者_StackOverflow社区eated a dynamic web project and I have deployed my servlet.java file under the WEB-INF folder. I have also added the servlet.jar file. How can I run the file as a java application?


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号