My first Servlet example

In this first and basic example we will create a web application that will ask for the name and then say ‘Hello name’

Start new Dynamic Web Project in Eclipse and name it ServletTest.

Create new class MyFirstServlet and extend the HttpServlet class. Implement two basic methods: doGet() and doPost(). In this example we will implement only POST method.

package si.matjazcerkvenik.servlets;

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 MyFirstServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public MyFirstServlet() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String name = request.getParameter("name");

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html>");
out.println("<head>");
out.println("<title>ServletTest example</title>");
out.println("</head>");
out.println("<body>");
out.println("<h3>Hello "+name+"</h3>");
out.println("<p>You are using POST</p>");
out.println("<a href=\"/ServletTest\">Click here to go back to input page</a>");

out.println("</body>");
out.println("</html>");
out.close();
}

}

Make new html page (Request1.html) which holds a form for input name. Set action parameter to match the servlet-mapping definition in web.xml.

<html>
<head>
<title>The servlet example</title>
</head>
<body>
<h3>My web application using POST</h3>
<form method="POST" action="MyFirstServlet">
<label for="name">Enter your name </label>
<input type="text" id="name" name="name" /><br>
<input type="submit" value="Submit Form" />
</form>
</body>
</html>

Open deployment descriptior (web.xml) and define the servlet name, servlet class and servlet-mapping.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>ServletTest</display-name>
<welcome-file-list>
<welcome-file>Request1.html</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>MyFirstServlet</display-name>
<servlet-name>MyFirstServlet</servlet-name>
<servlet-class>si.matjazcerkvenik.servlets.MyFirstServlet</servlet-class>
</servlet>
<servlet-mapping> <servlet-name>MyFirstServlet</servlet-name>
<url-pattern>/MyFirstServlet</url-pattern>
</servlet-mapping>
</web-app>

Deploy the application on Tomcat and see if it works:

http://localhost:8080/ServletTest/