How to create a Servlet with Eclipse and Tomcat

7 May 2012 By Nithya Vasudevan 114,227 views 31 Comments
34 Flares Twitter 1 Facebook 31 Google+ 2 34 Flares ×

Environment Used

  • JDK 6 (Java SE 6)
  • Eclipse Indigo IDE for Java EE Developers (3.7.1)
  • Apache Tomcat 6.x
  • Java EE 5 API (Servlet 2.5)

Setting up development environment

To install and configure Apache Tomcat in Eclipse IDE read this page .

Project Description

  • This example explains how to develop, deploy and run Servlet in Tomcat using Eclipse IDE.
  • We use Eclipse IDE for Java EE Developers which includes tools for creating Java EE and Web applications.

Creating Dynamic Web Project

To create a Servlet we need to create a new ‘Dynamic Web project’ which can be done in three ways,

  • Right click on Project Explorer -> New -> Dynamic Web Project
  • File menu -> New -> Dynamic Web Project
  • Click on the down arrow on New icon on toolbar -> Dynamic Web Project

Enter the project name as ‘FirstServlet‘ and make sure the Apache Tomcat v6.0 Target Runtime has been selected with the Dynamic web module version as 2.5 and click on ‘Finish‘ button.

You will see the Dynamic web project in the ‘Project Explorer‘ view.

Creating Servlet

  • Right click on src or Project -> New -> Servlet

  • Enter the Java package name as com.theopentutorials.servlets
  • Enter the Class name as HelloWorldServlet
  • Click on ‘Finish

In the doGet() method of your Servlet copy the following code.

package com.theopentutorials.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloWorldServlet
 */
public class HelloWorldServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
    public HelloWorldServlet() {
        super();
    }

    public void doGet(HttpServletRequest request, 
			HttpServletResponse response) 
		throws ServletException, IOException {
    	PrintWriter out = response.getWriter();
    	out.println("Hello World");
	}
}

Run the Servlet

Method 1:

Deploying Dynamic Web Project

Now we need to deploy the Servlet’s project ‘FirstServlet’ on server.
Deploying the project can be done in two ways,

  • Right click on the ‘FirstServlet’ Dynamic Web project -> Run As -> Run On Server. Select the existing ‘Tomcat v6.0 Server at localhost’ and click Finish.
  • Right click on ‘Tomcat v6.0 Server at localhost’ available in Servers view -> Add and Remove… -> Select the Servlet’s JAR file from the left pane and click Add-> and then Finish.
Start/Restart the Server

Right click on ‘Tomcat v6.0 Server at localhost’ from Servers view and click on Start if it has not yet been started.

Open any browser or Eclipse internal Web Browser and type the following URL for requesting Servlet
http://localhost:8080/FirstServlet/HelloWorldServlet

Method 2

This is simple and easy method and combines the three steps (deploying project, starting server and requesting Servlet) of method 1 in a single step.
You can run the Servlet in many ways,

  • Use Ctrl + F11 to run the Servlet and select the existing Server and Finish.
  • Right click on editor -> Run As-> Run on Server and select the existing Server and Finish.
  • Right click on Servlet file in Project Explorer -> Run As-> Run on Server and select the existing Server and Finish.

Eclipse Internal Web Browser will display the following output

Tags: , , , , , ,

  • Matej

    nice post, thanks!

  • Adeel Ahmed

    Thanks sister thanks a lot.You have saved my whole day.God bless you.This is really very informative

  • Howard

    I need help:

    I am getting the message PRoblem Occurred.
    Publishing to tomcat v7.0 server at localhost’ has encountered a problem
    Publishing the configuration ”

    The following classpaths are set (seen when I open launch configuration using eclipse)

    Bootstrap Entries
    JRE System Library [jre7]
    user entries:
    bootstrap.jar – C:\Program Files\Apache Software Foundation\Tomcat 7.0\bin

    The Details are the following:
    Error copying file to C:/Program Files/Apache Software Foundation/Tomcat 7.0/backup\catalina.policy: C:\Program Files\Apache Software Foundation\Tomcat 7.0\backup\catalina.policy (The system cannot find the path specified)
    C:\Program Files\Apache Software Foundation\Tomcat 7.0\backup\catalina.policy (The system cannot find the path specified)
    Error copying file to C:/Program Files/Apache Software Foundation/Tomcat 7.0/backup\catalina.properties: C:\Program Files\Apache Software Foundation\Tomcat 7.0\backup\catalina.properties (The system cannot find the path specified)
    C:\Program Files\Apache Software Foundation\Tomcat 7.0\backup\catalina.properties (The system cannot find the path specified)
    Error copying file to C:/Program Files/Apache Software Foundation/Tomcat 7.0/backup\context.xml: C:\Program Files\Apache Software Foundation\Tomcat 7.0\backup\context.xml (The system cannot find the path specified)
    C:\Program Files\Apache Software Foundation\Tomcat 7.0\backup\context.xml (The system cannot find the path specified)
    Error copying file to C:/Program Files/Apache Software Foundation/Tomcat 7.0/backup\server.xml: C:\Program Files\Apache Software Foundation\Tomcat 7.0\backup\server.xml (The system cannot find the path specified)
    C:\Program Files\Apache Software Foundation\Tomcat 7.0\backup\server.xml (The system cannot find the path specified)
    Error copying file to C:/Program Files/Apache Software Foundation/Tomcat 7.0/backup\tomcat-users.xml: C:\Program Files\Apache Software Foundation\Tomcat 7.0\backup\tomcat-users.xml (The system cannot find the path specified)
    C:\Program Files\Apache Software Foundation\Tomcat 7.0\backup\tomcat-users.xml (The system cannot find the path specified)
    Error copying file to C:/Program Files/Apache Software Foundation/Tomcat 7.0/backup\web.xml: C:\Program Files\Apache Software Foundation\Tomcat 7.0\backup\web.xml (The system cannot find the path specified)
    C:\Program Files\Apache Software Foundation\Tomcat 7.0\backup\web.xml (The system cannot find the path specified)

  • ravi

    hi
    i am using tomcat5.0,jdk 1.5
    problem is while deploying the project, the Eclipse Internal Web Browser is not displaying. whts the problem ?
    solve as early as possible………

  • Tarak

    Good and easy article thanx……

  • azahrudhin

    Simple and Easy , Thank you very much Nithya

  • vinayak

    thnx for useful info….

    but how we can create com.theopentutorial. package

    • http://theopentutorials.com Nithya Vasudevan

      refer step 5 in this tutorial.

  • ravi beli

    Nithya you are super, thanks for detailed steps.

    It will be helpful if you mention exact version of eclipse indigo.

    Thanks,
    Ravi Beli

  • Prasanta Kumar Sahoo

    Thanks a lot Nithya
    it is very useful to practice servlet. i am continuing mca at PTU.
    I am very happy feeling that your help will guide me.

  • Luca

    hi, thanks for the tutorial.
    I’m trying to do the same but I want to use the J2EE Preview server rather than Tomcat in Eclipse Juno on OSX Lion.
    However, when I run the project, I get this in the browser:

    Error 404 – Not Found

    No context on this server matched or handled this request…

    Can J2EE preview server actually be used to run servlets or do I need Tomcat??

    Thanks

  • Naveen

    Thanks a lot Vasudevan,it works fine for me.. :)

  • Brahma reddy

    Good and easy article thanx……

  • venkat

    hi, thanks for the tutorial.
    I got 404 error and details are like this
    type Status report
    message /fservlet/servlet/com.tcs.servlets.tservlet
    description The requested resource is not available.

    Please help me to solve this .I got stuck here for 2 days.

    • Ishara Samintha

      some time your web.xml file not like that

      My_Project

      index.html

      index.htm

      index.jsp

      default.html

      default.htm

      default.jsp

      HelloWorldServlet

      HelloWorldServlet

      com.theopentutorials.servlets.HelloWorldServlet

      HelloWorldServlet

      /myproject

      *specially and

  • senthilkumar

    hi.. i am try the sample program for servlet and html to connect the database in j2ee…. but error occuered this lines bellow…

    Dec 1, 2012 6:09:27 PM org.apache.catalina.core.AprLifecycleListener init
    INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:Program Files (x86)Javajre6in;C:WindowsSunJavain;C:Windowssystem32;C:Windows;C:/Program Files (x86)/Java/jre6/bin/client;C:/Program Files (x86)/Java/jre6/bin;C:/Program Files (x86)/Java/jre6/lib/i386;C:Program Files (x86)PC Connectivity Solution;C:Windowssystem32;C:Windows;C:WindowsSystem32Wbem;C:WindowsSystem32WindowsPowerShell 1.0;C:Program FilesIntelWiFiin;C:Program FilesCommon FilesIntelWirelessCommon;C:Program FilesBroadcomBroadcom 802.11 Network Adapter;c:Program Files (x86)Microsoft SQL Server@ToolsBinn;c:Program FilesMicrosoft SQL Server@ToolsBinn;c:Program FilesMicrosoft SQL Server@DTSBinn;C:Program Files (x86)Microsoft SQL Server@ToolsBinnVSShellCommon7IDE;C:Program Files (x86)Microsoft SQL Server@DTSBinn;C:Program Files (x86)Microsoft Visual Studio 9.0Common7IDEPrivateAssemblies;C:UserskumarkDesktopeclipse-jee-indigo-SR1-win32eclipse;;.
    Dec 1, 2012 6:09:27 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ‘source’ to ‘org.eclipse.jst.jee.server:Demo’ did not find a matching property.
    Dec 1, 2012 6:09:28 PM org.apache.coyote.http11.Http11Protocol init
    INFO: Initializing Coyote HTTP/1.1 on http-8080
    Dec 1, 2012 6:09:28 PM org.apache.catalina.startup.Catalina load
    INFO: Initialization processed in 411 ms
    Dec 1, 2012 6:09:28 PM org.apache.catalina.core.StandardService start
    INFO: Starting service Catalina
    Dec 1, 2012 6:09:28 PM org.apache.catalina.core.StandardEngine start
    INFO: Starting Servlet Engine: Apache Tomcat/6.0.35
    Dec 1, 2012 6:09:28 PM org.apache.catalina.core.ApplicationContext log
    INFO: Marking servlet AdminServlet as unavailable
    Dec 1, 2012 6:09:28 PM org.apache.catalina.core.ApplicationContext log
    SEVERE: Error loading WebappClassLoader
    context: /Demo
    delegate: false
    repositories:
    /WEB-INF/classes/
    ———-> Parent Classloader:
    org.apache.catalina.loader.StandardClassLoader@18fe7c3
    org.apache.axis.transport.http.AdminServlet
    java.lang.ClassNotFoundException: org.apache.axis.transport.http.AdminServlet
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1128)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1026)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4421)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4734)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
    at org.apache.catalina.core.StandardService.start(StandardService.java:525)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
    Dec 1, 2012 6:09:28 PM org.apache.catalina.core.StandardContext loadOnStartup
    SEVERE: Servlet /Demo threw load() exception
    java.lang.ClassNotFoundException: org.apache.axis.transport.http.AdminServlet
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1128)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1026)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4421)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4734)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
    at org.apache.catalina.core.StandardService.start(StandardService.java:525)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
    Dec 1, 2012 6:09:28 PM org.apache.coyote.http11.Http11Protocol start
    INFO: Starting Coyote HTTP/1.1 on http-8080
    Dec 1, 2012 6:09:28 PM org.apache.jk.common.ChannelSocket init
    INFO: JK: ajp13 listening on /0.0.0.0:8009
    Dec 1, 2012 6:09:28 PM org.apache.jk.server.JkMain start
    INFO: Jk running ID=0 time=0/19 config=null
    Dec 1, 2012 6:09:28 PM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 316 ms

  • swapnil

    I tried the same and got an error…..Http status : 404
    description : The requested resource is not available.

    • http://www.seelio.com/danielrobertson Daniel Robertson

      I got a 404 when I had a typo in my url. Make sure it’s localhost:8080/[projectname]/[servletname]/ and make sure Tomcat server is running successfully in Eclipse. It might have started but threw errors in the Servers tab on Eclipse without you noticing.

  • Netaji

    Very nice post and helpful post !

  • http://w3stutorial.blogspot.com Talib Hassan

    Nice and easy stuff
    also see it w3stutorial

  • nishanth

    thank you very much.i was getting some error ,even it was simple due to silly mistakes.2 days i was upset.thanks very much

  • imran

    Hello Mam, Your tutorials are more useful. And my doubt is am using Eclipse ADT plugin, here I can’t find option for create Servlet. I want to create servlet for android projects.

    • http://theopentutorials.com Nithya Vasudevan

      Change to Java EE perspective which can be done by clicking on the icon at top right corner. Now in package explorer right click->New->Dynamic Web Project.

  • Imran

    Thanks for your reply. and i can’t get Java EE in perspective.

    • http://theopentutorials.com Nithya Vasudevan

      Are you using Eclipse for Java EE developer IDE? Try this, in Windows menu -> Open Perspective -> Other… -> Java EE.

      • Imran

        No mam, am using Eclipse for Android Developer tool plugin.

  • Sandip

    If you are getting an error, please make sure you have /WEB-INF/web.xml with servlet mapping entry. By default, eclipse doesn’t generate web.xml for dynamic web project unless you have checked box on last page of wizard.

    You can generate web.xml by right click on project >> Java EE tools >> Generate Deployment Descriptor Stub.

  • Yves B

    I have encountered a problem when i trough to apply this tutoriel
    i use eclipse Kepler for java EE
    and Tomcat v7.0
    when i do a right click on my project and run on server
    eclipse send me this message :
    Starting Tomcat v7.0 Server at localhost’ has encountered a problem.
    Several ports (8080,8009) required by Tomcat v7.0 Server at locathost are already in use. The server may already be running in another process, or a system process may be using the port. To start this server you will need to stop the other process or change the port number(s).

    I changed ports 8080 to 8081 and 8005 to 8006 in tomcat folder/conf/server.xml
    but the same message with the ports 8080 and 8006
    please i need a help

  • sd

    Thanks for this article Nithya. Well written and just the thing I needed. God bless.

  • skSunny

    This tutorial is helpful but i have one problem in step 6.

    Right click on ‘Tomcat v6.0 Server at localhost’ available in Servers view -> Add and Remove… -> Select the Servlet’s JAR file from the left pane and click Add-> and then Finish.

    when i click into add and remove view, my left pane is empty.
    how can i fix it?

  • bhupal ponnada

    hi, thanks for the tutorial.
    I got 404 error and details are like this
    type Status report
    message /fservlet/servlet/com.tcs.servlets.tservlet
    description The requested resource is not available.

    Please help me to solve this .