Creating Servlet Using Eclipse IDE -


To create and run Servlet applications in Eclipse you need to download the following two files -

1- Eclipse IDE -

Eclipse is the most widely used open source IDE for creating java applications. You can download latest Eclipse IDE from the Eclipse website - https://www.eclipse.org/downloads/
Note - Make sure you have downloaded Eclipse IDE for JavaEE developers edition.

2- Apache Tomcat Server -

Apache Tomcat is an open source server created by Apache Software Foundation. You can download the latest version of Tomcat server from the following link - https://apache-tomcat.en.softonic.com/

Here we are using Eclipse Oxygen and Apache Tomcat8.0.27, The step by step process of using Eclipse to create and run Servlet applications is as follows -

1- Open Eclipse go to File -> New -> Dynamic Web Project.



2- It will open new Dynamic Web Project window. Enter project name, In our example project name is MyFirstServletDemo-



3- From Target runtime, select New Runtime button to configure Tomcat server -



4- It will open New Server Runtime Environment window, Select Apache tomcat version, that you have installed in your system, In our example, we selected Apache Tomcat v8.0.



5- Click Next and it will ask you to Browse the location of your Apache Tomcat Server. Browse the location of your installed Tomcat.



6- Click Finish, and it will configure Apache tomcat for your application.



7- From New Dynamic Web Project window click Next.



8- Again click Next and it will open the following windows -

Click on the Generated web.xml deployment descriptor checkbox. It will generate web.xml file for you. And finally click Finish
9- It will create a project structure as shown below -



10- Right Click on your project and go to New -> HTML File.

11- It will open New HTML File window, Name the file index.html and click Finish. It will create an index.html file in your WebContent Folder.



Note - This index.html file will be your default page i.e. when you run your project it will be your welcome page.
12- Make changes in your index.html page as shown below -
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="test">Click here to go to servlet</a>
</body>
</html>        

13- Right Click on src folder, go to New -> Package.



14- It will open New Java Package window, name the package, in our example package name is servs. And click on Finish



15- Now Right Click on servs package and go to New -> Class.



16- It will open a New Java Class window, name the class, in our example class name is MyServlet1. And finally click on Finish.



17- Add the following code to 'MyServlet1' class -
package servs;

import java.io.*;
import javax.servlet.*;

public class MyServlet1 implements Servlet
{
    
private ServletConfig sc;   
    
 public void init(ServletConfig config)throws ServletException
 {
     sc = config;
 }
 
 public ServletConfig getServletConfig()
 {
     return sc;
 }
 
 public void service(ServletRequest request, ServletResponse response)throws ServletException,IOException
 {
     try
     {
         response.setContentType("text/html");     
         PrintWriter out = response.getWriter();
         out.println("<html>");
         out.println("<head>");
         out.println("<title>My FIrst Servlet</title>");
         out.println("</head>");
         out.println("<body>");
         out.println("<h1>Welcome to Servlet</h1>");
         out.println("</body>");
         out.println("</html>");
     }
     catch(Exception ex)
     {
         System.out.println(ex);
     }
 }
 
 public String getServletInfo()
 {
     return "Info";
 }
 
 public void destroy()
 {
     
 }
}    
Program Description -
  • To convert 'MyServlet1' class into servlet, class implements 'Servlet' interface. As we allrady know Servlet interface contains 5 methods, so override these methods.
  • Except service() method, all the remaining 4 methods have the same above implementation in all programs.
  • Note that Servlet's do not have main() method, Whenever request came to servlet, it is the service() method that gets executed. So service() method will change in all program according to your requirements. Whatever output produced by servlet will be the output of your service() method. In this example it creates a simple html page with output 'Welcome to Servlet'.
  • service() method has 2 parameters- ServletRequest request and ServletResponse response - these corresponds to client request and response generated by server for the coming request.
  • response.setContentType("text/html"); - ServletResponse has method setContentType() that inform the client browser, what type of data is coming in response from server, so that browser can do the right things, for example launch a helper app like video player or pdf reader etc.
  • PrintWriter out = response.getWriter(); - java.io.PrintWriter object is required to write HTML text , we can get it from ServletResponse.
  • out.println() - PrintWriter has print() and println() methods that are used to write HTML text on web pages.

18- Open the web.xml file contained in WebContent -> WEB-INF folder and add the following code within web-app -
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" 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_3_0.xsd">
	<display-name>ServletInterfaceDemo</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	  <servlet>
        <servlet-name>demo</servlet-name>
        <servlet-class>servs.MyServlet1</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>demo</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>
</web-app>

web.xml (Deployment Descriptor) -
  • When we deploy our application on server, we need to create a XML file (web.xml), to tell the server, how to run our Servlet,s. This web.xml file is also called Deployment Descriptor.
  • In this file we have to put all the information regarding our servlets like servlet name, servlet class, url etc. Basically the main purpose of this is to create a mapping between client known public url('test' in our example) and servlet class name('MyServlet1' in our example).
  • In addition to servlet information , web.xml file also used to contain several other information that will be discussed ahead.
For mapping client known public url('test' in our example) and servlet class name('MyServlet1' in our example), we need to define following 2 XML tags -
<servlet>
It maps internal name defined in web.xml to your original servlet class name.
It contains two sub tags within it -
1- <servlet-name> - It contain internal name defined in web.xml (We used 'demo' in our example). This name can be anything, whatever you want.
2- <servlet-class> - It contain fully qualified servlet class name with package name ('servs.MyServlet1' in our example).
<servlet>
   <servlet-name>demo</servlet-name>
   <servlet-class>servs.MyServlet1</servlet-class>
</servlet>   
<servlet-mapping>
It maps internal name defined in web.xml to client known public url.It contains two sub tags within it -
1- <servlet-name> - It will be the same as we defined in <servlet> tag(i.e. demo in our example). 2- <url-pattern> - It will be the client known public url ('/test' in our example, because in index.html we use 'test' as hyperlink in anchor tag).
<servlet-mapping>
  <servlet-name>demo</servlet-name>
  <url-pattern>/test</url-pattern>
</servlet-mapping>         
19- TO run your project, Right Click on Your Project and go to Run As -> Run on Server.



20- It will open a Run on Server window, Select your server from the given list and click Finish.



21- Now it will show you the default page (index.html) on your web browser as follows -



Click on the link and it will show you the following output -