Servlet Example in Eclipse

Project Description :

This example explains how to develop, deploy and run Servlet in Tomcat using Eclipse IDE.

Follow the steps mentioned below to create servlet example in eclipse.


Step1: Creating Dynamic Web Project

We need to create a new "Dynamic Web project" which can be done by clicking on File menu -> New -> Dynamic Web Project

Project Description :

This example explains how to develop, deploy and run Servlet in Tomcat using Eclipse IDE.

Follow the steps mentioned below to create servlet example in eclipse.


Step1: Creating Dynamic Web Project

We need to create a new "Dynamic Web project" which can be done by clicking on File menu -> New -> Dynamic Web Project



Servlet Example in Eclipse

Provide the name of your Project as HelloServlet and select the target run time as Apache Tomact v6.0 and click on Finish as shown below.

Servlet Example in Eclipse


Step3: Create Servlet Class :

Create a package com.jwt.servlet in this project.You can create the package by Right Click on src -> New -> Package.

After creating the package create a class HelloServlet in this package.You can create the class by Right click on package -> New -> Class and provide the name of class as HelloServlet and click Finish.

Copy following code into this class.

package com.jwt.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;

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

Step 4: Create web.xml :

Add following code into web.xml file.

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
	<servlet>
		<servlet-name>HelloServlet</servlet-name>
		<servlet-class>com.jwt.servlets.HelloServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>HelloServlet</servlet-name>
		<url-pattern>/hello</url-pattern>
	</servlet-mapping>

</web-app>

Step 5: Run the Servlet :

To run the servlet Right Click on HelloServlet.java and then select Run as -> Run on Server and select Tomcat Server as shown below.

Servlet Example in Eclipse

Servlet Example in Eclipse

Now Click on Next and add your project on server and then click Finish as shown below

Servlet Example in Eclipse


Output in Browser :

Servlet Example in Eclipse




comments powered by Disqus