Categories: Servlet

Hello World Example in Servlet Interface

Servlets are Java classes which service HTTP requests and implement the javax.servlet.Servlet interface. Web application developers typically write servlets that extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface and is specially designed to handle HTTP requests.

Servlet Interface-

Servlet interface provides common behavior to all the servlets.

Servlet interface needs to be implemented for creating any servlet (either directly or indirectly). It provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and to destroy the servlet and 2 non-life cycle methods.

Methods of Servlet interface

There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods of servlet. These are invoked by the web container.

Method Description

  1. public void init(ServletConfig config) initializes the servlet. It is the life cycle method of servlet and invoked by the web container only once.
  2. public void service(ServletRequest request,ServletResponse response) provides response for the incoming request. It is invoked at each request by the web container.
  3. public void destroy() is invoked only once and indicates that servlet is being destroyed.
  4. public ServletConfig getServletConfig() returns the object of ServletConfig.
  5. public String getServletInfo() returns information about servlet such as writer, copyright, version etc.

 

Hello World Example in Servlet:

Following is the sample source code structure of a servlet example to write Hello World:

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
 
  private String message;

  public void init() throws ServletException
  {
      // Do required initialization
      message = "Hello World";
  }

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // Set response content type
      response.setContentType("text/html");

      // Actual logic goes here.
      PrintWriter out = response.getWriter();
      out.println("<h1>" + message + "</h1>");
  }
  
  public void destroy()
  {
      // do nothing.
  }
}

Compiling a Servlet:

Let us put above code if HelloWorld.java file and put this file in D:Servlet (Windows) or /usr/Servlet (Unix) then you would need to add these directories as well in CLASSPATH.

Assuming your environment is setup properly, go in Servlet directory and compile HelloWorld.java as follows:

If the servlet depends on any other libraries, you have to include those JAR files on your CLASSPATH as well. I have included only servlet-api.jar JAR file because I’m not using any other library in Hello World program.

If everything goes fine, above compilation would produce HelloWorld.class file in the same directory. Next section would explain how a compiled servlet would be deployed in production.

Servlet Deployment:

By default, a servlet application is located at the path C:Program Files (x86)Apache Software FoundationTomcat 7.0webappsROOT and the class file would reside in C:Program Files (x86)Apache Software FoundationTomcat 7.0webappsROOTWEB-INFclasses.

If you have a fully qualified class name of com.dineshonjava.MyServlet, then this servlet class must be located in C:Program Files (x86)Apache Software FoundationTomcat 7.0webappsROOTWEB-INF/classes/com/dineshonjava/MyServlet.class.

For now, let us copy HelloWorld.class into /webapps/ROOT/WEB-INF/classes and create following entries in web.xml file located in C:Program Files (x86)Apache Software FoundationTomcat 7.0webappsROOT/webapps/ROOT/WEB-INF/

<servlet>
        <servlet-name>HelloWorld</servlet-name>
        <servlet-class>HelloWorld</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloWorld</servlet-name>
        <url-pattern>/HelloWorld</url-pattern>
    </servlet-mapping>

Now let us start tomcat server using C:Program Files (x86)Apache Software FoundationTomcat 7.0binstartup.bat (on windows) or /bin/startup.sh (on Linux/Solaris etc.) and finally type http://localhost:8080/HelloWorld in browser’s address box. If everything goes fine, you would get following result:

 

 

<<Previous <<   || Index ||   >>Next >>

 

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago