Java Servlet Tutorial for Beginners

1- Instroduction

This document is based on:
  • Eclipse 4.5 (MARS) (ok for Eclipse 4.4 LUNA)

  • Servlet 3.0

  • Tomcat 8

Document History:
  • 05-07-2014: Document based on (Eclipse 4.3, Servlet 3.0, Tomcat 7.x)
  • 18-11-2014: Update to (Eclipse 4.4, Servlet 3.0, Tomcat 8.x)
  • 17-07-2015: Update to (Eclipse 4.5, Servlet 3.0, Tomcat 8.x, add more examples...)

2- What is Servlet?

Java Servlets are programs that run on a Web or Application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server.

Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically.

3- Servlet Lifecycle

The following figure illustrates the lifecycle of a servlet. Since it was created, processed requests from the users, until it was destroyed.
There are 5 step:
  1. Load Servlet Class.
  2. Create Instance of Servlet.
  3. Call the servlets init() method.
  4. Call the servlets service() method.
  5. Call the servlets destroy() method.

Step 1, 2 and 3 are executed only once, when the servlet is initially loaded. By default the servlet is not loaded until the first request is received for it. You can force the container to load the servlet when the container starts up though.

Step 4 is executed multiple times - once for every HTTP request to the servlet.
Step 5 is executed when the servlet container unloads the servlet.
 
You can see the following illustration to better understand the lifecycle of the Servlet.
When the request of users to Servlet, the servlet will call the method of  service() to serve the requirements of users, the  service() will call either  doGet() or  doPost().

Thus, when users request a Servlet, the servlet will be created at the time of the first request, and  will simultaneously call the  init() method of servlet to initialize it,  init() method is called only one time. Method of  destroy() is used to destroy the servlet, it will be called only once when removing deployment (undeloy) of web application or stop the web server.

4- Install Tomcat Web Server

To begin with Servlet, you need to download Tomcat Web Server and declare it with Eclipse. You can see the instructions at:

5- Create Web Project to start with Servlet

  • File/New/Other
  • Project Name: ServletTutorial
Project was created:
Create file index.html:
  • index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

    <h1>Hello World</h1>

</body>
</html>

6- Configure Eclipse to run Web on tomcat

So far, we have not yet done anything with Servlet. Now we configure it so that it can run that web application. Then we start with Servlet.
In eclipse, right-click on the Project ServletTutorial, select Properties:
Select the location of your Tomcat.
Right-click the project ServletTutorial, select "Run As / Run on Server".
Website is running on Eclipse browser.

Principle of operation:

When you type in the URL Website shows the content of index.html page, and this is understandable.

However, if you type in the URL: It means that you don't appoint a specific page, so webserver looks up default pages declared in <welcome-file> tag that you declared in web.xml for the answer.

Note: /ServletTutorial is called Context-Path. Each website has a Context-Path, and you can configure it with another value or let it empty. In the case of empty, you can access you web by:

  • http://localhost:8080
  • http://localhost:8080/index.html

When it runs with Tomcat, Context-Path is named as Project name.

Consider the following illustration:

7- Some classes participated in examples

Some classes participated in this example.
  • Constants.java
package org.o7planning.tutorial.beans;
 
public class Constants {
 
   public static final String ATTRIBUTE_USER_NAME_KEY ="ATTRIBUTE_USER_NAME_KEY";
    
   public static final String SESSION_USER_KEY ="SESSION_USER_KEY";
    
   public static final String CALLBACK_URL_KEY ="CALLBACK_URL_KEY";
    
}
  • UserInfo.java
package org.o7planning.tutorial.beans;

public class UserInfo {

    public String userName;
    private int post;
    private String country;
    
    public UserInfo(String userName, String country, int post)  {
        this.userName= userName;
        this.country= country;
        this.post= post;
    }

    public int getPost() {
        return post;
    }

    public void setPost(int post) {
        this.post = post;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public UserInfo(String userName) {
        this.userName = userName;
    }

    public String getUserName() {
        return this.userName;
    }
}

8- Create your first Servlet

HelloServlet.java
package org.o7planning.tutorial.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class HelloServlet extends HttpServlet {
   
   private static final long serialVersionUID = 1L;

   
   public HelloServlet() {
   }

   @Override
   protected void doGet(HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException {
       
       ServletOutputStream out = response.getOutputStream();
       
       out.println("<html>");
       out.println("<head><title>Hello Servlet</title></head>");
       
       out.println("<body>");
       out.println("<h3>Hello World</h3>");
       out.println("This is my first Servlet");
       out.println("</body>");
       out.println("<html>");
   }

   @Override
   protected void doPost(HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException {
       this.doGet(request, response);
   }

}
This is HelloServlet image that has been created with full of errors. This is simply because you have not declare Servlet library.
It is necessary to declare Servlet libraries, that are only Runtime libraries of Servlet. It is available on Web Servers. Here we use Tomcat, so we need to declare them.

Click right mouse on Project, select Properties:
Now the project has no error.
Next you need to declare HelloServlet and a path to access it in web.xml. You need to add the following configuration:
<!-- Define servlet, named helloServlet -->
<servlet>
   <servlet-name>helloServlet</servlet-name>
   <servlet-class>org.o7planning.tutorial.servlet.HelloServlet</servlet-class>
</servlet>

<!-- Defines the path to access this Servlet -->
<servlet-mapping>
   <servlet-name>helloServlet</servlet-name>
   <url-pattern>/hello</url-pattern>
</servlet-mapping>
web.xml
<?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"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id="WebApp_ID" version="3.0">
   <display-name>ServletTutorial</display-name>

   
   <servlet>
       <servlet-name>helloServlet</servlet-name>
       <servlet-class>org.o7planning.tutorial.servlet.HelloServlet</servlet-class>
   </servlet>

   <servlet-mapping>
       <servlet-name>helloServlet</servlet-name>
       <url-pattern>/hello</url-pattern>
   </servlet-mapping>


   <welcome-file-list>
       <welcome-file>index.html</welcome-file>
       <welcome-file>index.htm</welcome-file>
       <welcome-file>index.jsp</welcome-file>
       <welcome-file>default.html</welcome-file>
       <welcome-file>default.htm</welcome-file>
       <welcome-file>default.jsp</welcome-file>
   </welcome-file-list>


</web-app>
Rerun the project by right-click and select:
  • Run As/Run on Server
You can see its operating principle according to the illustration below:
When a Servlet is called, depending on the situation that either doGet (..) or doPost (..) will be called.
  • Specifically, when called doGet (..) and when called doPost (..) we will discuss later.
In doGet () or doPost (), you can retrieve the ServletOutputStream object , here is the output stream to send data to user's browser. Call ServletOutputStream.println(..) to write the data into the stream.
// The output stream to send data to user's browser

ServletOutputStream out = response.getOutputStream();

9- Init Parameter of Servlet

While declared servlet in web.xml you can setup the initialization parameters for it.
  • InitParamServlet.java
package org.o7planning.tutorial.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class InitParamServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private String emailSupport1;

    public InitParamServlet() {
    }

    // Method này luôn luôn được gọi 1 lần ngay sau khi đối tượng Servlet được tạo ra.
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        // Lấy ra thông tin tham số khởi tạo của Servlet
        // (Theo Cấu hình của Servlet này trong web.xml).
        this.emailSupport1 = config.getInitParameter("emailSupport1");
    }

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

        // Bạn có thể lấy ra tham số khởi tạo theo cách khác.
        String emailSupport2 = this.getServletConfig().getInitParameter("emailSupport2");

        ServletOutputStream out = response.getOutputStream();

        out.println("<html>");
        out.println("<head><title>Init Param</title></head>");

        out.println("<body>");
        out.println("<h3>Init Param</h3>");
        out.println("<p>emailSupport1 = " + this.emailSupport1 + "</p>");
        out.println("<p>emailSupport2 = " + emailSupport2 + "</p>");
        out.println("</body>");
        out.println("<html>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }

}
Configuring web.xml:
<servlet>
    <servlet-name>initParamServlet</servlet-name>
    <servlet-class>org.o7planning.tutorial.servlet.InitParamServlet</servlet-class>
    
    <init-param>
        <param-name>emailSupport1</param-name>
        <param-value>abc@example.com</param-value>
    </init-param>

    <init-param>
        <param-name>emailSupport2</param-name>
        <param-value>tom@example.com</param-value>
    </init-param>

</servlet>    


<servlet-mapping>
    <servlet-name>initParamServlet</servlet-name>
    <url-pattern>/initParam</url-pattern>
</servlet-mapping>
  • web.xml
<?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"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>ServletTutorial</display-name>

    
    <servlet>
        <servlet-name>helloServlet</servlet-name>
        <servlet-class>org.o7planning.tutorial.servlet.HelloServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>helloServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>


    <servlet>
        <servlet-name>initParamServlet</servlet-name>
        <servlet-class>org.o7planning.tutorial.servlet.InitParamServlet</servlet-class>
        
        <init-param>
            <param-name>emailSupport1</param-name>
            <param-value>abc@example.com</param-value>
        </init-param>
        
        <init-param>
            <param-name>emailSupport2</param-name>
            <param-value>tom@example.com</param-value>
        </init-param>
        
    </servlet>    
    
    
    <servlet-mapping>
        <servlet-name>initParamServlet</servlet-name>
        <url-pattern>/initParam</url-pattern>
    </servlet-mapping>


    
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>


</web-app>
Rerun web application and run URL:

10- Configuring Servlet with Annotations

With Servlet version 3.0 or higher you can configure the Servlet using Annotation, in this project we are using Servlet version 3.x so that we can use Annotation to configure. Consider an illustration.
  • AnnotationExampleServlet.java
package org.o7planning.tutorial.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


// You can configure one or multiple paths can access this Servlet
@WebServlet(urlPatterns = { "/annotationExample" , "/annExample" },
     initParams = {
         @WebInitParam(name = "emailSupport1", value = "abc@example.com"),
         @WebInitParam(name = "emailSupport2", value = "tom@example.com")
     }         
)
public class AnnotationExampleServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    
    private String emailSupport1;

    public AnnotationExampleServlet() {
    }


    // In any case, init() is guaranteed to be called before the servlet handles its first request.
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    
        this.emailSupport1 = config.getInitParameter("emailSupport1");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String emailSupport2 = this.getServletConfig().getInitParameter("emailSupport2");

        ServletOutputStream out = response.getOutputStream();

        out.println("<html>");
        out.println("<head><title>Init Param</title></head>");

        out.println("<body>");
        out.println("<h3>Servlet with Annotation configuration</h3>");
        out.println("<p>emailSupport1 = " + this.emailSupport1 + "</p>");
        out.println("<p>emailSupport2 = " + emailSupport2 + "</p>");
        out.println("</body>");
        out.println("<html>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }

}
You can access this Servlet in one of two following link:

11- Servlet Url Pattern

There are 4 ways to configure a path for Servlet:
URL Pattern Examples
/* http://example.com/contextPath
http://example.com/contextPath/status/abc
/status/abc/* http://example.com/contextPath/status/abc
http://example.com/contextPath/status/abc/mnp
http://example.com/contextPath/status/abc/mnp?date=today
http://example.com/contextPath/test/abc/mnp
*.map http://example.com/contextPath/status/abc.map
http://example.com/contextPath/status.map?date=today
http://example.com/contextPath/status/abc.MAP
/ Đây là Servlet mặc định.
When the user enters a link on browser it will be sent to WebContainer. WebContainer must decide whether
Servlet will service this request from users. 

The figure below illustrates how WebContainer decided to use Servlet to service request from the client.
For example create a Servlet url-pattern with asterisk:
  • url-pattern = "/any/*";
  • AsteriskServlet.java
package org.o7planning.tutorial.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = { "/any/*" })
public class AsteriskServlet extends HttpServlet {

   private static final long serialVersionUID = 1L;

   public AsteriskServlet() {
   }

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

       ServletOutputStream out = response.getOutputStream();

       out.println("<html>");
       out.println("<head><title>Asterisk</title></head>");

       out.println("<body>");
       
       out.println("<h3>Hi, your URL match /any/*</h3>");
       
       out.println("</body>");
       out.println("<html>");
   }

   @Override
   protected void doPost(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
       this.doGet(request, response);
   }

}
The following URLs are serviced by AsteriskServlet (/any/*):

Default Servlet:

Servlet with url-pattern  = /

As a default servlet, servlet will be used for processing the requests that the path does not match any url-pattern of the Servlet is declared in your application.
See an example of the default servlet:
  • MyDefaultServlet.java
package org.o7planning.tutorial.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = { "/" })
public class MyDefaultServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public MyDefaultServlet() {
    }

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

        ServletOutputStream out = response.getOutputStream();

        out.println("<html>");
        out.println("<head><title>Page not found</title></head>");

        out.println("<body>");
        out.println("<h3>Sorry! Page not found</h3>");
        out.println("<h1>404</h1>");
        out.println("Message from servlet: " + this.getClass().getName());
        out.println("</body>");
        out.println("<html>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }

}
You can rerun the Web application, and access path:
Link above have servletPath = /news/tomAndJerry, does not match the url-pattern you've declared. Meanwhile "default Servlet " will serve this request.

12- Get the basic information of the Servlet

You can retrieve the information relating to the time served by Servlet instance:
  1. Information requests from the client.
  2. Server Information 
  3. Client Information
  4. Header information sent on request
  5. ....
  • ExampleInfoServlet.java
package org.o7planning.tutorial.servlet;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/other/exampleInfo")
public class ExampleInfoServlet extends HttpServlet {

   private static final long serialVersionUID = 1L;

   public ExampleInfoServlet() {
       super();
   }

   @Override
   protected void doGet(HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException {
       ServletOutputStream out = response.getOutputStream();

       out.println("<style> span {color:blue;} </style>");

       String requestURL = request.getRequestURL().toString();
       out.println("<br><span>requestURL:</span>");
       out.println(requestURL);

       String requestURI = request.getRequestURI();
       out.println("<br><span>requestURI:</span>");
       out.println(requestURI);

       String contextPath = request.getContextPath();
       out.println("<br><span>contextPath:</span>");
       out.println(contextPath);

       out.println("<br><span>servletPath:</span>");
       String servletPath = request.getServletPath();
       out.println(servletPath);

       String queryString = request.getQueryString();
       out.println("<br><span>queryString:</span>");
       out.println(queryString);

       String param1 = request.getParameter("text1");
       out.println("<br><span>getParameter text1:</span>");
       out.println(param1);

       String param2 = request.getParameter("text2");
       out.println("<br><span>getParameter text2:</span>");
       out.println(param2);

       // Server Infos
       out.println("<br><br><b>Server info:</b>");

       out.println("<br><span>serverName:</span>");
       String serverName = request.getServerName();
       out.println(serverName);

       out.println("<br><span>serverPort:</span>");
       int serverPort = request.getServerPort();
       out.println(serverPort + "");

       // Client Infos
       out.println("<br><br><b>Client info:</b>");

       out.println("<br><span>remoteAddr:</span>");
       String remoteAddr = request.getRemoteAddr();
       out.println(remoteAddr);

       out.println("<br><span>remoteHost:</span>");
       String remoteHost = request.getRemoteHost();
       out.println(remoteHost);

       out.println("<br><span>remoteHost:</span>");
       int remotePort = request.getRemotePort();
       out.println(remotePort + "");

       out.println("<br><span>remoteUser:</span>");
       String remoteUser = request.getRemoteUser();
       out.println(remoteUser);

       // Header Infos
       out.println("<br><br><b>headers:</b>");

       Enumeration<String> headers = request.getHeaderNames();
       while (headers.hasMoreElements()) {
           String header = headers.nextElement();
           out.println("<br><span>" + header + "</span>: "
                   + request.getHeader(header));
       }

       // Servlet Context info:
       out.println("<br><br><b>Servlet Context info:</b>");
       ServletContext servletContext = request.getServletContext();

       // Location of web application in hard disk
       out.println("<br><span>realPath:</span>");
       String realPath = servletContext.getRealPath("");
       out.println(realPath);
   }

   @Override
   protected void doPost(HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException {
       this.doGet(request, response);
   }

}
Please see the illustration below, with the information that you are interested:
Rerun the web application and access the link:
Result:

13- Forward

Forward: When a request to a Servlet, it can forward the request to another page (or another servlet). Address on the user's browser is still the linkof the first page, but the content is created by the forwarded page.

The page was forwarded to, compulsory is a page (or servlet) located on your web application.

With Forward you can use request.setAttribute() to transfer data from page 1 to page 2.
  • ForwardDemoServlet.java
package org.o7planning.tutorial.servlet.other;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.o7planning.tutorial.beans.Constants;

@WebServlet("/other/forwardDemo")
public class ForwardDemoServlet extends HttpServlet {
   private static final long serialVersionUID = 1L;

   @Override
   protected void doGet(HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException {
       // Get parameter on URL      
       // http://localhost:8080/ServletTutorial/other/forwardDemo?forward=true        
       String forward = request.getParameter("forward");

       if ("true".equals(forward)) {
           System.out.println("Forward to ShowMeServlet");

           // Send data to next page (page forward to)
           request.setAttribute(Constants.ATTRIBUTE_USER_NAME_KEY,
                   "Hi, I'm Tom come from Walt Disney !");

           RequestDispatcher dispatcher = request.getServletContext()
                   .getRequestDispatcher("/showMe");
           dispatcher.forward(request, response);

           return;
       }
       ServletOutputStream out = response.getOutputStream();
       out.println("<h3>Text of ForwardDemoServlet</h3>");
       out.println("- servletPath=" + request.getServletPath());
   }

   @Override
   protected void doPost(HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException {
       this.doGet(request, response);
   }

}
Rerun Web app and run respectively 2 URL:
Case 1: There is no forward. The data on the page is generated by  ForwardDemoServlet .
Case 2: foward transfers to ShowMeServlet. In this case the URL on the page is unchanged while the data is generated by ShowMeServlet.
Forward is often used in some cases such as when user requests servlet A. However, this page is required to log in before.Servlet A checks the user's login and if not yet done, it would move to servlet Login.
Back to the RequestDispatcher, we have two ways to get RequestDispatcher object.
request.getServletContext ().getRequestDispatcher(url) returns RequestDispatcher is located relative to the contextPath (position relative to the root directory of the website).
  • http://localhost:8080/contextPath
  • http://localhost:8080/ServletTutorial
request.getRequestDispatcher(url) returns RequestDispatcher is located relative to the current page.
  • http://localhost:8080/ServletTutorial/other/forwardDemo

 Note:

  • Redirect allows you to navigate to pages, including ones outside Website.
  • Forward only allows to move to pages within Website, and can transfer data between two pages through request.setAttribute.

14- Redirect

Redirect: When a request from the user to a Servlet (page A), this servlet can redirect requests to another page (page B), and the end of its mission.  The page is redirected to  may be the page in your application, or may be a any page.

Unlike Forward. With Redirect you can not use request.setAttribute(..) to transfer data from page A to page B.
  • ShowMeServlet.java
package org.o7planning.tutorial.servlet.other;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.o7planning.tutorial.beans.Constants;

@WebServlet("/showMe")
public class ShowMeServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;

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

     // Get value of Attribute (Sent from forward page)
     String value = (String) request
             .getAttribute(Constants.ATTRIBUTE_USER_NAME_KEY);

     ServletOutputStream out = response.getOutputStream();

     out.println("<h1>ShowMeServlet</h1>");
     out.println(value);
 }

 @Override
 protected void doPost(HttpServletRequest request,
         HttpServletResponse response) throws ServletException, IOException {
     this.doGet(request, response);
 }

}
  • RedirectDemoServlet.java
package org.o7planning.tutorial.servlet.other;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/other/redirectDemo")
public class RedirectDemoServlet extends HttpServlet {

   private static final long serialVersionUID = 1L;

   @Override
   protected void doGet(HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException {
       // Get parameter on the URL
       // http://localhost:8080/ServletTutorial/other/redirectDemo?redirect=true
       String redirect = request.getParameter("redirect");

       if ("true".equals(redirect)) {
           System.out.println("Redirect to ShowMeServlet");
           // ContextPath always be "" or "/contextPath".    

           String contextPath = request.getContextPath();

           // ==> /ServletTutorial/showMe
           response.sendRedirect(contextPath + "/showMe");
           return;
       }

       ServletOutputStream out = response.getOutputStream();
       out.println("<h3>Text of RedirectDemoServlet</h3>");
       out.println("- servletPath=" + request.getServletPath());
   }

   @Override
   protected void doPost(HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException {
       this.doGet(request, response);
   }

}
Rerun webserver and run 2 URL respectively in your browser:
For first URL:
With the second path,the request redirects to  ShowMeServlet. The URL you see on browser is the path of servlet  ShowMeServlet.

15- Session

The HttpSession object represents a user session. A user session contains information about the user across multiple HTTP requests.

When a user enters your site for the first time, the user is given a unique ID to identify his session by. This ID is typically stored in a cookie or in a request parameter.

Đây là đoạn code để bạn truy cập vào đối tượng session:
protected void doGet(HttpServletRequest request,
   HttpServletResponse response)
       throws ServletException, IOException {

   HttpSession session = request.getSession();
}
You can store values in the session object, and retrieve them later. First, let's see how you can store values in the session object:
// Get HttpSession object
HttpSession session = request.getSession();

// Suppose user has successfully logged.
UserInfo loginedInfo = new UserInfo("Tom", "USA", 5);

// Storing user information in Session under 1 attribute.
// You can retrieve user information in Session
session.setAttribute(Constants.SESSION_USER_KEY, loginedInfo);
And retrieve information stored in Session in a certain page.
// Get HttpSession object.
HttpSession session = request.getSession();

// Retrieving UserInfo object is stored in session
UserInfo loginedInfo = (UserInfo) session.getAttribute(Constants.SESSION_USER_KEY);
View full example:
  • LoginServlet.java
package org.o7planning.tutorial.servlet.session;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.o7planning.tutorial.beans.Constants;
import org.o7planning.tutorial.beans.UserInfo;

@WebServlet(urlPatterns = { "/login" })
public class LoginServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public LoginServlet() {
    }

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

        ServletOutputStream out = response.getOutputStream();


        // Get HttpSession object
        HttpSession session = request.getSession();

        // Suppose a user has successfully logged.
        UserInfo loginedInfo = new UserInfo("Tom", "USA", 5);
       
        // Storing user information in Session under 1 attribute.
        // You can retrieve user information in Session
        session.setAttribute(Constants.SESSION_USER_KEY, loginedInfo);

        out.println("<html>");
        out.println("<head><title>Session example</title></head>");

        out.println("<body>");
        out.println("<h3>You are logined!, info stored in session</h3>");

        out.println("<a href='userInfo'>View User Info</a>");
        out.println("</body>");
        out.println("<html>");
    }

}
  • UserInfoServlet.java
package org.o7planning.tutorial.servlet.session;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.o7planning.tutorial.beans.Constants;
import org.o7planning.tutorial.beans.UserInfo;

@WebServlet(urlPatterns = { "/userInfo" })
public class UserInfoServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public UserInfoServlet() {
    }

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

        ServletOutputStream out = response.getOutputStream();

 
        // Get HttpSession object
        HttpSession session = request.getSession();


        // Get UserInfo object stored in session after user login successful.
        UserInfo loginedInfo = (UserInfo) session.getAttribute(Constants.SESSION_USER_KEY);

        // If not logined, redirect to login page (LoginServlet).
        if (loginedInfo == null) {
            // ==> /ServletTutorial/login
            response.sendRedirect(this.getServletContext().getContextPath() + "/login");
            return;
        }

        out.println("<html>");
        out.println("<head><title>Session example</title></head>");

        out.println("<body>");

        out.println("<h3>User Info:</h3>");

        out.println("<p>User Name:" + loginedInfo.getUserName() + "</p>");
        out.println("<p>Country:" + loginedInfo.getCountry() + "</p>");
        out.println("<p>Post:" + loginedInfo.getPost() + "</p>");

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

}
Running the example:

16- Servlet-Filter Tutorial

Next you can see more document about Servlet-Filter:

17- JSP Tutorial

Next you can see "Java JSP tutorial" at: