Friday, 31 October 2014

Servlet Error Handling

Servlet application will not be perfect until it works on all negative or positive scenario.So, Error handling is also required during servlet programming. In this chapter I will explain about how to handle servlet errors.

Whenever servlet will throw any error by any reason whether it is because of resource not found or authentication issue, etc...then error stack-trace will be taken by web container and converted to html and simply send by response to render to the browser. So, end user will not be having understanding  about stack-trace.

Servlet container provides way to handle any kind of error and sends specific response or it can redirect to other page in case of error happen. So, rather than sending stack-trace as it is to the end user, we can navigate user to some other meaningful page so, that end user easily can understand that something went wrong.But to do this container should aware about this i.e. for which error what action should take or which page should redirect.

Hence to tell to servlet container we need to configure the deployment descriptor (web.xml) i.e. for which error code or which exeception type, which servlet should called.

Web.xml

 <error-page>
    <error-code>404</error-code>
    <location>/ExceptionHandler</location>
  </error-page>
   
  <error-page>
    <exception-type>javax.servlet.ServletException</exception-type>
    <location>/ExceptionHandler</location>
 </error-page>

error-page tag is used to handle error in servlet. It can either handled for error code or for exception type and location inner tag is used to tell about servlet location.In above example whenever error code 404 will arise or if ServletException will arise then ExceptionHandler Servlet will be invoked.
So, we can say any error can be handled by servlet.

Before servlet container invokes the servlet to handle the exception, it sets some attributes in the request to get useful information about the exception, some of them are javax.servlet.error.exception, javax.servlet.error.status_code, javax.servlet.error.servlet_name and javax.servlet.error.request_uri

For Example Below is given ExceptionHandler shows how to handle the specific error



protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        Throwable throwable = (Throwable) request
                .getAttribute("javax.servlet.error.exception");
        Integer statusCode = (Integer) request
                .getAttribute("javax.servlet.error.status_code");
        String servletName = (String) request
                .getAttribute("javax.servlet.error.servlet_name");
        String requestUri = (String) request
                .getAttribute("javax.servlet.error.request_uri");
    
        PrintWriter out = response.getWriter();
          out.write("<html><head><title>Error Details</title></head><body>");
           
          if(statusCode != 500){
              out.write("Status Code:"+statusCode+"<br>");
              out.write("Requested URI:"+requestUri);
          }else{
              out.write("<ul><li>Servlet Name:"+servletName+"</li>");
              out.write("<li>Exception Name:"+throwable.getClass().getName()+"</li>");
              out.write("<li>Requested URI:"+requestUri+"</li>");
              out.write("<li>Exception Message:"+throwable.getMessage()+"</li>");
              out.write("</ul>");
          }
           
          out.write("<br><br>");
          out.write("</body></html>");
}

If there are multiple error-page entries, let’s say one for Throwable and one for IOException and application throws FileNotFoundException then it will be handled by error handler of IOException.
You can also use JSP page as exception handler, just provide the location of jsp file rather than servlet mapping.


Thanks!!!!

Monday, 27 October 2014

Creating wifi hotspot in windows by CMD/Command Prompt

Creating wifi hotspot-
I know this tutorial is about java but here creating wifi hotspot in windows, is different but should know to all the guys, because sometime situation comes where you don't have wireless router in home or office and still you want to connect your PC's or mobile devices through wifi hotspot.
Don't worry!!! you can still connect your devices through wireless hosted network but this is introduced from window7. You need to create only virtual wireless adapter to connect all the devices. I will explain some steps here to do this by command prompt-
  1. Open command prompt in administrator mode by choosing run as administrator.
  2. Check whether your PC has installed Wlan driver and does it supports hosted network, to check this use netsh command, type in cmd-  netsh wlan show drivers

  3. If hosted network supports yes then again use netsh command to create new hosted network-
    netsh wlan set hostednetwork mode=allow ssid=<user-defined-hotspotname> key=<password>
  4.  Now you start the hosted network by command-  netsh wlan start <user-defined-hotspotname>
  5. Now go to network and sharing center and click on "change adapter settings" select Local area connection on which internet is working, right click and click on property and select sharing tab and enable allow other network users option.

That's it now you can connect wifi hosted network in other devices where ever you want use it. And after usage done you cant stop this by using below command-
netsh wlan stop <user-defined-hotspotname>


As you can see to create wifi hotspot I have used netsh command but what is netsh command?
Netsh is a command-line scripting utility that allows you to, either locally or remotely, display or modify the network configuration of a computer that is currently running. Netsh also provides a scripting feature that allows you to run a group of commands in batch mode against a specified computer. Netsh can also save a configuration script in a text file for archival purposes or to help you configure other servers.

Thanks!!!!

Friday, 24 October 2014

Servlet Filter

Servlet Filter is a object inside web container, which is used to intercept the request and response before sending to server resource and browser.


In above diagram you can see that browser send the request to access the server request but in middle, Filter Object intercept the browser request and take action against the request and forward to server resource. Similarly Filter intercept in response also which is coming from Server Resource and take against it before sending to the browser.

Keeping Filter inside web container has various use-cases like(but use-case are not limited)-
  • User Authentication or Authorization-Blocking requests based on user identity.
  • Server load handle-Reject the request if server load is too much.
  • Logging and auditing -Tracking users of a web application
  • Data compression- Making downloads smaller.
  • Server Code Debug- Debug the server resource for performance tuning
In order to create the servlet filter, Filter interface (javax.servlet.Filter) need to be implemented.
Method decryption of Filter interface is given below-

void destroy()
          Called by the web container to indicate to a filter that it is being taken out of service.
 void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
          The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain.
FilterChain is an object provided by the servlet container to the developer giving a view into the invocation chain of a filtered request for a resource. Filters use the FilterChain to invoke the next filter in the chain, or if the calling filter is the last filter in the chain, to invoke the resource at the end of the chain. 
 void init(FilterConfig filterConfig)
          Called by the web container to indicate to a filter that it is being placed into service.
This filter configuration object used by a servlet container to pass information to a filter during initialization.

Let's take one example- whenever browser will send request along with allow parameter then only filter will allow to send request to the server otherwise it will reject.

MyServletFilter.java
 
package com.rkclass; 
import javax.servlet.*;
import java.io.IOException;


public class MyServletFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain filterChain)
    throws IOException, ServletException {
 
       String myParam = request.getParameter("allow");

       if("allow".equals(myParam)){
          filterChain.doFilter(request, response);
       }
    }

    public void destroy() {
    }
}
 

 
Web.xml
 
<filter>
    <filter-name>myFilter</filter-name>
    <filter-class>com.rkclass.MyServletFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>myFilter</filter-name>
    <url-pattern>*.do</url-pattern>
</filter-mapping> 

Sunday, 12 October 2014

Servlet Listener

ServletListener is a small program which will listen to some events. Events can be anything like session event, context event, context attribute event, request event.
In this chapter I will explain-
  1. ServletContextListener
  2. ServletContextAttributeListener
  3. HttpSessionListener
  4. HttpSessionAttributeListener
  5. ServletRequestListener
ServletContextListener-
I explained the ServletContext in previous chapter. So, I am assuming you know about ServletContext.
ServletContext is a object that consist config to Share among Servlets.

Now assume you want execute some piece of code, when ever application context initialize or destroyed. In this scenario you need to know some events when context is initialize or destroyed.
Don't worry!!! javax.servlet.ServletContextListener interface provide this.

Below is the methods description of SessionContextListener-

 void contextDestroyed(ServletContextEvent sce)
          Receives notification that the ServletContext is about to be shut down.
 void contextInitialized(ServletContextEvent sce)
          Receives notification that the web application initialization process is starting.

For example I want to load the property file when I start the server.

Create the Listener-

package com.rkclass.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.*;
@WebListener
public class MyContextListener implements ServletContextListener {
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext ctx = servletContextEvent.getServletContext();
        try {
          String fileName = ctx.getInitParameter("configFile");
          System.out.println(fileName);
          File file = new File(fileName);
          FileInputStream fis = new FileInputStream(file);
  
          Properties p = new Properties();

          p.load(fis);
        } catch (IOException e) {
             e.printStackTrace();
        }
    }
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        ServletContext ctx = servletContextEvent.getServletContext();
        System.out.println("Context destroyed");
       
    }
     
}

Web.xml-

<listener>
    <listener-class>com.rkclass.listener.MyContextListener</listener-class>
</listener>

Now Property is ready to use.Whenever context will initialize Property will be loaded.

ServletContextAttributeListener
This interface and extends the java.util.EventListener class.Whenever attribute of SessionContext added/changed/removed this listener receive the notification event. But to get the notification, your servlet context attribute listener class should be register in the web container i.e. web.xml.

Below is the method description of this listener-
void attributeAdded(ServletContextAttributeEvent event)
          Receives notification that an attribute has been added to the ServletContext.
 void attributeRemoved(ServletContextAttributeEvent event)
          Receives notification that an attribute has been removed from the ServletContext.
 void attributeReplaced(ServletContextAttributeEvent event)
           

For Example-

Create the Listener-

package com.rkclass.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.annotation.WebListener;
import java.util.*;
@WebListener
public class MyContextAttributeListener implements ServletContextAttributeListener {
     
    public void attributeAdded(ServletContextAttributeEvent scab){      
            System.out.println("attribute Added");
    }

    public void attributeRemoved(ServletContextAttributeEvent scab) {
       System.out.println("attribute Removed"); 
    }

    public void attributeReplaced(ServletContextAttributeEvent scab) {       
       System.out.println("attribute Replaced");       
    }
     
}


Web.xml-

<listener>
    <listener-class>com.rkclass.listener.MyContextAttributeListener</listener-class>
</listener>

MyServlet.java-

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
     PrintWriter out = response.getWriter();
     ServletContext sc = getServletContext();
     sc.setAttribute("name", "XXX");
     sc.setAttribute("age", "23");
     sc.removeAttribute("name");
}    

you can verify the output log and you will get to know that when setting the attribute in ServletContext then attributeAdded() is getting invoked and when removeAttribute() is called then attributeRemoved() method is getting invoked by container.

HttpSessionListener
Whenever changes to the list of active sessions happen in a web application. i.e. new session is created or destroyed then this listener is notified.

Below is the method descriptor of this listener-
void sessionCreated(HttpSessionEvent se)
          Notification that a session was created.
 void sessionDestroyed(HttpSessionEvent se)
          Notification that a session is about to be invalidated.

For example suppose we want count the active session-

MyHttpSessionListener.java

package com.rkclass.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class MyHttpSessionListener implements HttpSessionListener{
  private int activeSession=0;  
   
  @Override
  public void sessionCreated(HttpSessionEvent arg0) {
 activeSession++;
 System.out.println("sessionCreated");
  }
 
  @Override
  public void sessionDestroyed(HttpSessionEvent arg0) {
 activeSession--;
 System.out.println("sessionDestroyed");
  } 
     
}

Web.xml-

<listener>
    <listener-class>com.rkclass.listener.MyHttpSessionListener</listener-class>
</listener>

 MyServlet.java-


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

  HttpSession session = request.getSession(); //sessionCreated() will be execute
  //do something with session 
  session.invalidate();  //sessionDestroyed() will be execute
}    


HttpSessionAttributeListener
Whenever attibute added/deleted/replaced to the session object this listener will be notified by web container.

Below is the method descriptor of this listener
void attributeAdded(HttpSessionBindingEvent se)
          Notification that an attribute has been added to a session.
 void attributeRemoved(HttpSessionBindingEvent se)
          Notification that an attribute has been removed from a session.
 void attributeReplaced(HttpSessionBindingEvent se)
          Notification that an attribute has been replaced in a session.

MyHttpSessionAttributeListener.java

package com.rkclass.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class MyHttpSessionAttributeListener implements HttpSessionAttributeListener{

   
     @Override
     public void attributeAdded(HttpSessionBindingEvent event) { 
      String attributeName = event.getName(); 
      Object attributeValue = event.getValue(); 
      System.out.println(attributeName + " : " + attributeValue);
     }
 
     @Override
     public void attributeRemoved(HttpSessionBindingEvent event) {
 String attributeName = event.getName(); 
        Object attributeValue = event.getValue();
 System.out.println(attributeName + " : " + attributeValue);
    }
 
     @Override
     public void attributeReplaced(HttpSessionBindingEvent event) {
        String attributeName = event.getName();
 Object attributeValue = event.getValue();
 System.out.println(attributeName + " : " + attributeValue); 
     }
}

Web.xml-

<listener>
    <listener-class>com.rkclass.listener.MyHttpSessionAttributeListener </listener-class>
</listener>

 MyServlet.java-


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

  HttpSession session = request.getSession(); 
  session.setAttribute("name", "xxx"); //attributeAdded() will be execute
  session.setAttribute("name", "yyy"); //attributeReplaced() will be execute
  session.removeAttribute("name"); //attributeRemoved() will be execute
  session.invalidate(); 
}    

ServletRequestListener 
Whenever request coming into the the web container or request going out from the web container then this listener is notified.

Below is the method description of this listener
void requestDestroyed(ServletRequestEvent sre)
          Receives notification that a ServletRequest is about to go out of scope of the web application.
 void requestInitialized(ServletRequestEvent sre)
          Receives notification that a ServletRequest is about to come into scope of the web application.

Wednesday, 8 October 2014

ServletContext vs ServletConfig

SerlvetConfig-
ServletConfig is a interface which is implemented by GenericServlet, and this Servlet or HttpServlet (sub class of GenericServlet) can be used to create your own Servlet class. Single servlet configuration passed by Servlet container to init() method to initialize some parameter on Servlet.

These parameter is defined in descriptor file (web.xml).<init-param> tag will be used under <servlet> tag.This Config object is public to a servlet and scope will be, as long as a servlet is executing, ServletConfig object will be available, it will be destroyed once the servlet execution is completed.

For example-

Web.xml file-

<servlet>
 <servlet-name>servlet-config</servlet-name>
 <servlet-class>com.test.MyServlet</servlet-class>
 <init-param>
  <param-name>name</param-name>
  <param-value>XXXXXX</param-value>
 </init-param>
</servlet>

MyServlet.java file- 

public void init(ServletConfig config) throws ServletException
{
    ServletContext sc = getServletContext();
    getServletContext().getInitParameter("name"); 
}

Now the question is when is difference between int() method and int(ServletConfig) method.

public void init(ServletConfig config)throws ServletException
This method Called by the servlet container to indicate to a servlet that the servlet is being placed into service.See Servlet#init. This implementation stores the ServletConfig object it receives from the servlet container for later use. When overriding this form of the method, call super.init(config).

public void init() throws ServletException
A convenience method which can be overridden so that there's no need to call super.init(config).Instead of overriding init(ServletConfig), simply override this method and it will be called by GenericServlet.init(ServletConfig config). The ServletConfig object can still be retrieved via getServletConfig().

ServletContext-
ServletContext is implemented by the servlet container for all servlet to communicate with its servlet container.This object is contained within the ServletConfig object. And to access the ServletContext  use ServletConfig object within a servlet. This again is specified in descriptor file (web.xml) under <context-param> tags, as this is not specific to specific servlet so, present globally i.e. outside of <servlet> tag.Mainly This is used to access common information among servlet, which is store in <context-param> tag.

ServletContext object is global to entire web application. Object of ServletContext will be created at the time of web application deployment.And scope will be, as long as web application is executing, ServletContext object will be available, and it will be destroyed once the application is removed from the server.ServletContext object will be available even before giving the first request.

For examplet-
Web.xml file

<context-param>
    <param-name>globalVariable</param-name>
    <param-value>Hello To all servlet</param-value>
</context-param> 

MyServlet.java file

public void doGet(HttpServletRequest request, HttpServletResponse response)
 throws IOException{
  PrintWriter pw = response.getWriter();
        pw.println(getServletContext().getInitParameter("globalVariable"));
}

Sunday, 5 October 2014

HttpSession, Session in java

In previous chapter I have explained various ways of session tracking (cookie, hidden form field, url rewriting). In this chapter I will explain one more way of session tracking which is HttpSession.

Sessions are server-side files that contain user information, while Cookies are client-side files that contain user information. Sessions have a unique identifier that maps them to specific users. This identifier can be passed in the URL or saved into a session cookie.

Create the session
 
The HttpServletRequest interface provides two methods to get the object of HttpSession (javax.servlet.http.HttpSession)-
  1. public HttpSession getSession():Returns the current session associated with this request, or if the request does not have a session, creates one.
  2. public HttpSession getSession(boolean create):Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
For example-

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

    HttpSession session = request.getSession();

}

 But apart from these methods, some method are also commonly use-
  1. public String getId():Returns a string containing the unique identifier value.
  2. public long getCreationTime():Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
  3. public long getLastAccessedTime():Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.
  4. public void invalidate():Invalidates this session then unbinds any objects bound to it.

Let's try to understand what happen, when create the session by below diagram-



Above diagram shows that when session object with unique id created by container, This sessions identifier that maps them to specific users. This identifier can be passed in the URL or saved into a session cookie. And later consecutive browser request will include this identifier with it and send to container to identify correct user specific session object.

Store the value/attribute inside Session
To store the value inside session object we can use setAttribute() method. It has two parameter first is for key and second is for value.Session internally uses map to store the value. Hence takes key/value pare from parameter.
  
session.setAttribute("key", "value");
e.g. 
session.setAttribute("userName", "XXXX");


Retrieve the value/attribute from session
To retrieve the value from session we can use getAttribute method()
e.g.
String userName = (String) session.getAttribute("userName");

Delete the session

To delete the session use invalidate() method-

e.g

// Get the existing session.
HttpSession session = request.getSession(false);

// Invalidate the existing session, to
ensure that all previous session data(s) for the user is removed //from the context.
if(session!=null) {
    session.invalidate();
}


But sometime when user login to the application after Session Times out,we may not
need his previous session data and we need to create a new session for the user.


// Get the existing session.
HttpSession session = request.getSession(false);

if(session!=null) {
session.invalidate();
}
// Create a new session for the user.
session = request.getSession(true);

We can also use setMaxInactiveInterval(int interval) method to set the minimum time to session will be kept alive by the server when it doesn't get accessed by a client. if you use this method then explicitly no need to call invalidate() method.
By default time session timeout for tomcat is 30min

We can also configure this timeout value in descriptor file -

<session-config>
    <session-timeout>10</session-timeout>
</session-config

Let's take example of session-

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();


// getting current HttpSession associated with this request or, if there
// is no current session and create is true, returns a new session.
HttpSession session = request.getSession(true);

out.println("Session ID: " + session.getId() );
out.println("Is it a new session: " + session.isNew());
out.println("Session Creation time: " + session.getCreationTime());
out.println(new Date(session.getCreationTime()));
out.println("Last accessed time: " + session.getLastAccessedTime());
out.println(new Date(session.getLastAccessedTime()));
out.println("Max in active time interval: " + session.getMaxInactiveInterval());

 

// Checks whether the requested session ID came in as a cookie
out.println("Session ID came in as a cookie: "+ request.isRequestedSessionIdFromCookie());

   Enumeration names = session.getAttributeNames();
   while (names.hasMoreElements()) {
      String name = (String) names.nextElement();
      String value = session.getAttribute(name).toString();
      out.println(name + " = " + value );
   }

}

Friday, 3 October 2014

URL Rewriting

I explained in previous chapter if browser has disabled the cookie then use hidden form field for session tracking. But in hidden form field user easily can identified by seeing URL that what are all the information transmitting in query string-
e.g.
http://serverhost:port/applicationname/servlet.do?username=xxx&age=xx&..................

So, we can say end user easily can stole the information and hack the data if http request method is GET.

But Java provides another way of session tracking URL Rewriting. In this mechanism requested URL will be modified by adding some extra information. Extra information is nothing but placing a session id in the URL called jsessionid.

The question comes in mind what is JSESSIONID and why it is necessary?
The answerw will be- If Web server is using cookie for session management/tracking it creates and sends JSESSIONID cookie in the response to the client and then client sends it back to server in subsequent http requests. So, we can say this is a one identifier to identify the cookie, If  client has disabled cookie then Container uses URL rewriting for managing session on which jsessionid is appended into URL as shown below-
e.g.
http://serverhost:port/applicationname/servlet.do;jsessionid=363F3D316

Let's create example to understand URL rewriting. In this example doGet() method of servlet encoding the url and then writing to the out stream.


protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    String contextPath = request.getContextPath();
    String encodedUrl = response.encodeURL(contextPath +  
         "/WelcomePage.jsp");

    out.println("<html>");
    out.println("<head>");
    out.println("<title>URL Rewriter</title>");
    out.println("</head>");
    out.println("<body><center>");
    out.println("<h2>URL rewriting Example</h2>");
    out.println("For welcome page - <a href=\"" + encodedUrl+ "\">
        Click Here</a>.");
    out.println("</center></body>");
    out.println("</html>");
}

WelcomePage.jsp page

<html>
<body>
<h2 align="center">Welcome to URL rewriting example</h2>
</body>
</html>

But make sure URL rewriting has significant security risks. Session id appears in the URL, it may be easily seen by third parties and end user can-
  • end users often copy and paste such links without knowing the attached session id compromises their security
  • server log files usually record the 'Referer' header, which will record session ids in the log
Third-party access to session id's simply means that private user information is wide open to attack. Thus, many argue that URL rewriting is a dangerous practice, and should be avoided. If cookies are used instead, then the session id does not appear in the URL.

It's possible that some web sites may use cookies to track user browsing patterns. As a result, some users turn off cookies in an attempt to protect their privacy. However, given the seriousness of the above security issue, many would argue that turning off cookies is actually much worse for user privacy. That is, the risk of compromising personal data through session hijacking seems to far outweigh concerns about tracking personal browsing patterns.

Next chapter I will explain about session. click here to go to next chapter

Wednesday, 1 October 2014

Hidden Form Field

As I explain in previous chapter that cookie has drawback that if browser has disabled cookie then cookie will not work. So, work around of previous approach is hidden form field.

In this approach we use hidden form field to store user states so that this user states can be circulated among servlets.

<input type="hidden" name="Language" value="English">

e.g
Login page where user will submit username and password and this username will be stored in hidden field of another page and it will be showed in top of home page.

1. Create  the login page-

<form action="loginaction"
    Name:<input type="text" name="userName"/><br/> 
    Password:<input type="password" name="password"/><br/> 
   <input type="submit" value="submit"/> 
 </form> 

2. Create the servlet which will handle login action-
  1. import java.io.*;  
  2. import javax.servlet.*;  
  3. import javax.servlet.http.*;  
  4.   
  5. public class LoginServlet extends HttpServlet {  
  6. public void doGet(HttpServletRequest request, HttpServletResponse response){  
  7.         try{  
  8.         String userName= request.getParameter("userName");
  9.         String password = request.getParameter("password");  
  10.         if( userName!= null &&password != null && isAuthUser(userName,password )){
  11.             response.setContentType("text/html");  
  12.             PrintWriter out = response.getWriter();  
  13.             out.print("Welcome "+userName);  
  14.             out.print("<form action='homeServlet'>");  
  15.             out.print("<input type='hidden' name='username' value='"+userName+"'>");  
  16.             out.print("<input type='submit' value='home page'>");  
  17.             out.print("</form>");  
  18.             out.close(); 
  19.         }
  20.        }catch(Exception e){System.out.println(e);}  
  21.     }  
  22.   
3. Create the HomeServlet which will generate page by using hidden field value. 
  1. import java.io.*;  
  2. import javax.servlet.*;  
  3. import javax.servlet.http.*;  
  4.   
  5. public class HomeServlet extends HttpServlet {  
  6. public void doGet(HttpServletRequest request, HttpServletResponse response){  
  7.         try{  
  8.         String userName= request.getParameter("username");      
  9.         if( userName!= null ){
  10.             response.setContentType("text/html");  
  11.             PrintWriter out = response.getWriter();  
  12.             out.print("User: "+userName);  
  13.            //other home page creation logic
  14.             out.close(); 
  15.         }
  16.        }catch(Exception e){System.out.println(e);}  
  17.     }  
  18.   
  19. }

4. Create the web.xml file and put servlet mapping. 

  1. <web-app>  
  2.   
  3. <servlet>  
  4. <servlet-name>login-servlet</servlet-name>  
  5. <servlet-class>LoginServlet</servlet-class>  
  6. </servlet>  
  7.   
  8. <servlet-mapping>  
  9. <servlet-name>login-servlet</servlet-name>  
  10. <url-pattern>/loginaction</url-pattern>  
  11. </servlet-mapping>  
  12.   
  13. <servlet>  
  14. <servlet-name>home-servlet</servlet-name>  
  15. <servlet-class>HomeServlet</servlet-class>  
  16. </servlet>  
  17.   
  18. <servlet-mapping>  
  19. <servlet-name>home-servlet</servlet-name>  
  20. <url-pattern>/homeServlet</url-pattern>  
  21. </servlet-mapping>  
  22.   
  23. </web-app> 

In above example you can see username which is entered in login page and validated in LoginServlet later it stored in hidden input box and this value is used in HomeServlet. So, you can see username is shared among two servlet.