Writing First Servlet HelloWorld Web Application

Developing HelloWorld Servlet Web Application is easy and requires only 2 files. In this tutorial, folder structure, web.xml, servlet class are provided.


Folder Structure

webapps
   |_ helloworldservlet
    |_ WEB-INF
    |_ classes
      |_ HelloWorld.java
      |_ HelloWorld.class
    |_ web.xml

web.xml

<web-app>
 <servlet>
     <servlet-name>myservlet</servlet-name>
     <servlet-class>HelloWorld</servlet-class>
 </servlet>

 <servlet-mapping>
     <servlet-name>myservlet</servlet-name>
     <url-pattern>/hw</url-pattern>
    </servlet-mapping>
</web-app>

HelloWorld.java

import javax.servlet.http.*;  
import javax.servlet.*;  
import java.io.*;  
public class HelloWorld extends HttpServlet  
{  
 public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException  
 {  
 PrintWriter pw=res.getWriter();  
 res.setContentType("text/html");  
 pw.println("<h1>Hello World!</h1>");  
 }  
}

javax.servlet.http.*: Contains HttpServlet, HttpServletRequest, HttpServletResponse classes (used here).

javax.servlet.*: Contains ServletException (used here).

java.io.*: Contains PrintWriter, IOException (used here).

doGet(): For url type submission, submission through url.

PrintWriter: Part of the java.io package.

res.setContentType("text/html"): Set content type to html, because the page is html. Optional.

pw.println("<h1>Hello World!</h1>"): Present in the PrintWriter class, write HelloWorld! within <h1> (here).