The method getRemoteUser() of the HttpServletRequest gives the username of the client. With the remote user’s name, a servlet can save information about each client. Over the long term, it can remember each individual’s preferences. For the short term, it can remember the series of pages, viewed by the client and use them to add a sense of state to a stateless HTTP protocol.

A simple servlet that uses getRemoteUser() can greet its clients by name and remember when each last logged in as shown in the example below:

 import java.io.*;
import java.sql.Date;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class PersonalizedWelcome extends HttpServlet{
    
    Hashtable accesses = new Hashtable();
    
    public void doGet(HttpServletRequest req,HttpServletResponse res)
            throws ServletException,IOException{
        
        res.setContentType("text/plain");
        PrintWriter out= res.getWriter();
        
        // Some introductory HTML...
        String remoteUser = req.getRemoteUser();
        
        // See if the client is allowed
        if(remoteUser == null){
            out.println("Welcome");
        } else{
            out.println("Welcome " + remoteUser + "!");
            Date lastAccess = (Date)accesses.get(remoteUser);
            if(lastAccess==null){
                out.println("This last visit was "  + accesses.get(remoteUser));
            }
            if(remoteUser.equals("Rohit")){
                out.println("Shall we play  a game");
            }
            accesses.put(remoteUser, new Date());
        }
        
        //continue handling the request
    }
}