Developing Servlets Application

Steps to Create Servlets Application

A web server is required to develop a servlet application. We are using Apache Tomcat server to develop servlet application.

Following are the steps to develop a servlet application:
1. Create directory structure
2. Create a servlet
3. Compile the servlet
4. Create a deployment descriptor
5. Start the server and deploy the application

1. Create directory structure

There is a unique directory structure that must be followed to create Servlet application. This structure tells where to put the different types of files.

directory structure

2. Create a Servlet

//ServletDemo.java

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class ServletDemo extends HttpServlet
{
     public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
     {
         res.setContentType("text/html");
         PrintWriter pw = res.getWriter();
         pw.println("<html><body>");
         pw.println("First Program of Servlet");
         pw.println("</body></html>");
         pw.close();
     }
}

3. Compile the Servlet program

Assuming the classpath and environment is setup properly, run the above Java program.

C:\javac ServletDemo.java

After compiling the Java file, paste the class file of servlet in WEB-INF/classes directory.

4. Create a deployment descriptor

The deployment descriptor is an xml file. It is used to map URL to servlet class, defining error page.

//web.xml

<web-app>
    <servlet>
        <servlet-name>World</servlet-name>
        <servlet-class>ServletDemo</servlet-class>
    </servlet>

    <servlet-mapping>
         <servlet-name>Hello</servlet-name>
         <url-pattern>/Hello</url-pattern>
    </servlet-mapping>
</web-app>


Note:
  • Copy the ServletDemoclass into <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes.
  • Save the web.xml file in <Tomcat-installation directoryt>/webapps/ROOT/WEB-INF/

5. Start the server and deploy the application

Now start the Tomcat server by using

<Tomcat installation-direcory>\bin\startup.bat

Open browser and type

http://localhost:8080/demo/Hello