Tuesday, 26 July 2016

Extending Servlets



Extending  Servlets

#: What is Session?
Answer: when a user makes a page request to the server, the server creates a temporary session to identify that user. So when that same user goes to another page on that site, the server identifies that user. So a session is a small and temporary unique connection between a server and the user enabling it to identify that user across multiple page requests or visits to that site

Session Management:
Session management is to use the API provided by your application server to identify the user across multiple page requests. Note that every server has it's own set of API for session management, since we are talking about 'Managing Sessions with Java Servlets', we will be making use of the Servlet API 2.2 which almost all of the Java application servers support.
HttpSession Interface
Managing sessions has been made extremely easy by the Servlet API since there is just a single interface involved and that interface is
HttpSession interface. You then invoke methods of this interface to interact with the user.
Methods of HttpSession Interface
Before going into the details of using different methods of this interface, lets first see what are different methods available to us.
  • getAttribute(), getAttributeNames(), setAttribute(), removeAttribute() These methods are used to set, get and remove objects from a user session. We will see later how to use them.
  • getId() Every session created by the server has a unique 'id' associated with it in order to identify this session from other sessions. This method returns the 'id' of this session.
  • getCreationTime() Simple returns a long value indicating the date and time this session was created, meaning there by that you get the time this user first accessed your site.
  • getLastAccessedTime() Returns a long value indicating the last time user accessed any resource on this server.
# The Stateless Environment
Answer: Stateless VS Stateful In ususal interactive programming, you deal with a stateful environments. That means, your app is in a session with the user. You have multiple queries and responses during this single session and you keep some sort of processing state (usually in main memory).
A typical example is a mailorder application. Following is a typical pseudo-code for such an application:
log on user
do
      allow user to browse database
      add new selection to set of selections
until user has finished selection phase
if any products were selected
      ask for shipping/billing information
      enter selection as an order
log off user
This is a typical sample in a procedure oriented environment. Not really neat for an event driven GUI interface, but one thing is common to such applications: the application keeps state information of the user session. This processing state is preserved across multiple interactions (here the product selection phase). The preservation of the processing state is done by the environment itself, typically by letting you application staying loaded during the multiple requests. Your application is always in control of what's going on and can handle it. This is a typical example of a stateful environment.
A stateless environment, on the other hand, does not offer these benefits to your application. The environment won't do anything to preserve the session state. Each request and response is a new one and not related to any other.
As you might guess, there are of course ways to implement stateful sessions in stateless environements. This is what this document is all about.

# Solutions to providing state
Answer:  When the Hyper-Text Transfer Protocol (HTTP) was developed, its designers chose to create a protocol which does not maintain a persistent connection. Each request made by a Web browser, for an image, an HTML page, or other Web object, is made via a new connection. It would have been handy if Web browsers established a single connection, through which multiple requests could be made. Indeed, this feature has been introduced in HTTP 1.1, with the keep-alive feature. This feature comes too late though for server-side programmers, as support for legacy browsers and Web servers must be maintained. Without an ongoing session, however, it is difficult for developers to maintain state across HTTP requests. This ability is critical though for all but the simplest of server-side applications. A shopping cart, for example, needs to maintain a list of items and have this list associated with a specific user.
 Developers are an inventive bunch and quickly found solutions. The simplest of all was to encode hidden parameters inside an HTML form, such as the username and type of transaction being made. Though not evident to the user, additional state information has been added to the form, which will be passed when the form is submitted. If every form included a hidden field indicating the user, then it would be possible to track user actions across HTTP requests. Of course, additional information can also be included, such as the
type of operation being performed, as well as the focus of the operation. The following HTML code illustrates the use of hidden fields:
<form action="/servlet/order" method=post>
<input type="hidden" name=userid value="5532211">
<input type="hidden" name=operation  value="add">
<input type="hidden" name=product_id value="4432A">
Product ID : 4432A
Quantity   : <input type="quantity" value=1>
<input type=submit>
</form>
A variation on this theme is to use hyperlinks, which generate HTTP GET requests. Often a hyperlink is better than an HTML form, as most users are more comfortable with hyperlinks than buttons. Parameters can be added to the end of each URL, so that state information is passed when the next connection is made. For example, every hyperlink on the page could contain a userID code to allow user activity to be tracked. This information can be fetched by a servlet using
javax.servlet.http.HttpServletRequest.getParameter(String)
just as a standard CGI parameter would.
<a href="/servlet/shopping?userID=5532211>View Shopping Cart</a>
Whether a hyperlink or an HTML form is used, this state information must be included every time a request is made, so that subsequent requests can gain access to it. If your servlet misses a URL or a hidden variable is missed from a form, the state information is lost. Such solutions are crude but effective. They do the job but are an inelegant and overly complex way of maintaining state across HTTP requests. A better way of maintaining state information is to use persistent client state cookies.


NOTE: Stateless and Stateful  Stateless protocol (like HTTP) A protocol that can't remember previous connections and can't distinguish one client's  request from that of another.  Stateful protocol (like FTP)   does not require you to create a new   connection for every request  maintains the user's credentials throughout  the session

# Session Management with cookies
Answer:  The HTTP state management mechanism specifies a way to create a stateful session with HTTP requests and responses.
Generally, HTTP request/response pairs are independent of each other. However, the state management mechanism enables clients and servers that can exchange state information to put these pairs in a larger context, which is called a session. The state information used to create and maintain the session is called a cookie.
Note: A cookie is a piece of data that can be stored in a browser's cache. If you visit a web site and then revisit it, the cookie data can be used to identify you as a return visitor. Cookies enable state information, such as an online shopping cart, to be remembered. A cookie can be short term, holding data for a single web session, that is, until you close the browser, or a cookie can be longer term, holding data for a week or a year.
 Web browsers and e-commerce sites use HTTP to communicate. Since HTTP is a stateless protocol (meaning that each command is executed independently without any knowledge of the commands that came before it), there must be a way to manage sessions between the browser side and the server side.
WebSphere Commerce supports two types of session management: cookie-based and URL rewriting.
Cookie-based session management
When cookie-based session management is used, a message (cookie) containing user's information is sent to the browser by the Web server. This cookie is sent back to the server when the user tries to access certain pages. By sending back the cookie, the server is able to identify the user and retrieves the user's session from the session database; thus, maintaining the user's session. A cookie-based session ends when the user logs off or closes the browser. Cookie-based session management is secure and has performance benefits. Cookie-based session management is secure because it uses an identification tag that only flows over SSL (Secure Sockets Layer).  Cookie-based session management offers significant performance benefits because the WebSphere Commerce caching mechanism only supports cookie-based sessions, and not URL rewriting. Cookie-based session management is recommended for customer sessions.

If you are not using URL rewriting and you want to ensure that users have cookies enabled on their browsers, check Cookie acceptance test on the Session Management page of Configuration Manager. This informs the customer that if their browser does not support cookies, or if they have turned off cookies, they need a browser that supports cookies to browse the WebSphere Commerce site.

For security reasons, cookie-based session management uses two types of cookies:
Non-secure session cookie
Used to manage session data. Contains the session ID, negotiated language, current store and the customers preferred currency when the cookie is constructed. This cookie can flow between the browser and server under either SSL or non-SSL connection. There are two types of non-secure session cookies:

1.A WebSphere Application Server session cookie is based on the servlet HTTP session standard. WebSphere Application Server cookies persist to memory or to the database in a multinode deployment. For more information.

2.A WebSphere Commerce session cookie is internal to WebSphere Commerce and does not persist to the database.

Secure authentication cookie
Used to manage authentication data. An authentication cookie flow over SSL and is time stamped for maximum security. This is the cookie used to authenticate the user; whenever a sensitive command is executed, for example, the DoPaymentCmd which asks for a users credit card number. There is minimal risk that this cookie could be stolen and used by an unauthorized user. Authentication code cookies are always generated by WebSphere Commerce whenever cookie based session management is in use.

Both the session and authentication code cookies are required to view secure pages.
For cookie errors the CookieErrorView is called under the following circumstances:
·   The user has logged in from another location with the same Logon ID.
·   The cookie became corrupted, or was tampered with or both.
·   If cookie acceptance is set to "true" and the user's browser does not support cookies.
# Session Management with Encoded URLs
Answer:  With URL rewriting, all links that are returned to the browser or that get redirected have the session ID appended to them. When the user clicks these links, the rewritten form of the URL is sent to the server as part of the client's request. The servlet engine recognizes the session ID in the URL and saves it for obtaining the proper object for this user. To use URL rewriting, HTML files (files with .html or .htm extensions) cannot be used for links. To use URL rewriting, JSP files must be used for display purposes. A session with URL rewriting expires when the customer logs off.
Note: WebSphere Commerce dynamic caching and URL rewriting cannot interoperate. With URL rewriting turned on, you need to disable WebSphere Commerce dynamic caching.
The administrator can choose to support either only cookie-based session management or both cookie-based and URL rewriting session management. If WebSphere Commerce only supports cookie-based, customers' browsers must be able to accept cookies. If both cookie-based and URL rewriting are selected, WebSphere Commerce first attempts to use cookies to manage sessions; if the customer's browser is set to not accept cookies then URL rewriting is used.
URL rewriting is the lowest common denominator of session tracking. When a client will not accept a cookie, URL rewriting may be used by the server as the basis for session tracking. URL rewriting involves adding data, a session ID, to the URL path that is interpreted by the container to associate the request with a session.
The session ID must be encoded as a path parameter in the URL string. The name of the parameter must be 'jsessionid' (lowercase !). Here is an example of a URL containing encoded path information:
http://www.myserver.com/catalog/index.html;jsessionid=1234                                             
                                                      
package javax.servlet.http;

public interface HttpServletRequest extends javax.servlet.ServletRequest {
       
        public boolean isRequestedSessionIdFromCookie();
        public boolean isRequestedSessionIdFromURL();
        public boolean isRequestedSessionIdValid();
}                                    
There are 2 methods in the HttpServletResponse for URL rewriting:
  • encodeURL(String)
Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL. For example, if the browser supports cookies, or session tracking is turned off, URL encoding is unnecessary. For robust session tracking, all URLs emitted by a servlet should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies.
  • encodeRedirectURL(String)
Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged. The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL. Because the rules for making this determination can differ from those used to decide whether to encode a normal link, this method is separated from the encodeURL method. All URLs sent to the HttpServletResponse.sendRedirect method should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies.
package javax.servlet.http;
                                     
public interface HttpServletResponse extends javax.servlet.ServletResponse {

        public java.lang.String encodeURL(java.lang.String url);
        public java.lang.String encodeRedirectURL(java.lang.String url)

}
                                     
public void doGet(HttpServletRequest req, HttpServletResponse res)
               throws IOException, ServletException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
       
        out.print("<form action='");
        out.print(response.encodeURL("SessionExample"));
        out.print("' ");
        out.println("method='post'>");
}



# Session Management in Servlets
Answer: Developing session management in servlets : This information, combined with the coding example SessionSample.java,  provides a programming model for implementing sessions in your own servlets.

Procedure   
1. Get the HttpSession object. To obtain a session, use the getSession() method of the javax.servlet.http.HttpServletRequest object in the Java Servlet 2.3 API.

When you first obtain the HttpSession object, the Session Management facility uses one of three ways to establish tracking of the session: cookies, URL rewriting, or Secure Sockets Layer (SSL) information.
Assume the Session Management facility uses cookies. In such a case, the Session Management facility creates a unique session ID and typically sends it back to the browser as a cookie. Each subsequent request from this user (at the same browser) passes the cookie containing the session ID, and the Session Management facility uses this ID to find the user's existing HttpSession object.

In Step 1 of the code sample, the Boolean(create) is set to true so that the HttpSession object is created if it does not already exist. (With the Servlet 2.3 API, the javax.servlet.http.HttpServletRequest.getSession() method with no boolean defaults to true and creates a session if one does not already exist for this user.)

2. Store and retrieve user-defined data in the session.  After a session is established, you can add and retrieve user-defined data to the session. The HttpSession object has methods similar to those in java.util.Dictionary for adding, retrieving, and removing arbitrary Java objects.

 In Step 2 of the code sample, the servlet reads an integer object from the HttpSession, increments it, and writes it back. You can use any name to identify values in the HttpSession object. The code sample uses the name sessiontest.counter.

Because the HttpSession object is shared among servlets that the user might access, consider adopting a site-wide naming convention to avoid conflicts.
3. (Optional) Output an HTML response page containing data from the HttpSession object.

4. Provide feedback to the user that an action has taken place during the session. You may want to pass HTML code to the client browser indicating that an action has occurred. For example, in
step 3 of the code sample, the servlet generates a Web page that is returned to the user and displays the value of the sessiontest.counter each time the user visits that Web page during the session.
5.(Optional) Notify Listeners. Objects stored in a session that implement the javax.servlet.http.HttpSessionBindingListener interface are notified when the session is preparing to end and become invalidated. This notice enables you to perform post-session processing, including permanently saving the data changes made during the session to a database.
6. End the session. You can end a session: * Automatically with the Session Management facility if a session is inactive for a specified time. The administrators provide a way to specify the amount of time after which to invalidate a session. * By coding the servlet to call the invalidate() method on the session object.

Example
import java.io.*;   import java.util.*;   import javax.servlet.*;   import javax.servlet.http.*;

public class SessionSample  extends HttpServlet {
  public void doGet (HttpServletRequest request, HttpServletResponse response) 
       throws ServletException, IOException {

   // Step 1: Get the Session object
      boolean create = true;        
      HttpSession session = request.getSession(create);
   // Step 2: Get the session data value
      Integer ival = (Integer)             
      session.getAttribute ("sessiontest.counter");        
      if (ival == null) ival = new Integer (1);        
      else ival = new Integer (ival.intValue () + 1);          
      session.setAttribute ("sessiontest.counter", ival);      

   // Step 3: Output the page
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.println("<html>"); 
      out.println("<head><title>Session Tracking Test</title></head>");
      out.println("<body>");
      out.println("<h1>Session Tracking Test</h1>");
      out.println ("You have hit this page " + ival + " times" + "<br>");
      out.println ("Your " + request.getHeader("Cookie"));
      out.println("</body></html>");   
   }
}

No comments:

Post a Comment