Servlet Hello World
This tutorial is the standard Hello World program using Java Servlet.
Using an IDE is the best choice to do development. It will help to increase the productivity.
If you are in the early days of learning, like in college or school then you can use a simple text editor like Notepad++.
My IDE of choice is Eclipse, but this tutorial is not tied with it. These are just my suggestions and you can go with any editors.
Web Application Structure
First lets start with a shell project structure and we should have directories created as shown below:
Note the webapps that’s where the application should be deployed in tomcat.
- webapps – Folder of Tomcat where the project should be put to run.
- hello-world – Application root folder. It can contain all the static files and other resources like images, css created in this. In real time will have lots of CSS, image etc and those should be create separate folder under this root.
- WEB-INF – will contain the web.xml file
- classes – will contain the servlet classes.
- lib – will contain the dependent jar files.
Hello World Servlet
package com.javapapers.servlet.introduction;
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 HelloWorld extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<html><body>");
out.println("Hello World!");
out.println("</body></html>");
out.close();
}
}
web.xml
In this web.xml we have defined Servlet mapping. Go through this linked tutorial to know about servlet mapping.
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <display-name>Servlet Hello World</display-name> <servlet> <servlet-name>helloWorldServlet</servlet-name> <servlet-class>com.javapapers.servlet.introduction.HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>helloWorldServlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app>
This Servlet Hello World web application contains only the above two files. Download the complete project