servlets-2

download servlets-2

of 28

Transcript of servlets-2

  • 8/12/2019 servlets-2

    1/28

  • 8/12/2019 servlets-2

    2/28

    Topics to be covered

    Statelessness of HTTP protocol

    Business logic needs stateful protocol

    What is a Session?

    What is Session ID?

    What is Session Tracking?

    Hidden form fields

    URL Rewriting

    Cookies

    Session Tracking API

  • 8/12/2019 servlets-2

    3/28

    Topics to be covered

    Creating session

    Setting new Attribute in Session Deleting session data

    Servlet Context scope

    Context scope attributes Redirect to another webpage

    Mechanism used by sendRedirct

    Using RequestDispatcher

    CookeisAnatomy of cookeis

    Seting cookies with servlet

    Reading cookies with Servlet

  • 8/12/2019 servlets-2

    4/28

    Statelessness of HTTP protocol Series of actions in http request-response protocol :

    A client opens a connection

    Requests some resource

    Server receives the request

    Generates the response

    Sends back the response to the client

    Closes the connection

    Once the connection is closed, the server cannot rememberany information about the client.

    So server considers the next request from the same client as afresh client, with no relation to the previous request.

    So HTTP protocol is called stateless protocol.

  • 8/12/2019 servlets-2

    5/28

    Business logic needs stateful protocol

    When there is a need to maintain the conversationalstate, session tracking is needed.

    Ex: In a shopping cart application a client keeps on adding

    items into his cart using multiple requests.

    When every request is made, the server should identifyin which clients cart the item is to be added.

    So in this scenario, there is a certain need for session

    tracking. Solution is, when a client makes a request it should

    introduce itself by providing unique identifier everytime.

  • 8/12/2019 servlets-2

    6/28

    What is a Session?

    A session is a conversation between the server and a client.A conversation consists series of continuous request and

    response.

    A Session refers to sequence of all the requests that a single

    client makes to a server for a particular period.

    A session is specific to the user and for each user a new

    session is created to track all the request from that user.

    Every user has a separate session and separate sessionvariable is associated with that session.

    In case of web applications the default time-out value for

    session variable is 20 minutes, which can be changed as per

    the requirement.

  • 8/12/2019 servlets-2

    7/28

    What is Session ID?

    A session ID is an unique identification string usually along, random and alpha-numeric string.

    It is transmitted between the client and the server.

    Session IDs are usually stored in the cookies, URLs (in caseurl rewriting) and hidden fields of Web pages.

  • 8/12/2019 servlets-2

    8/28

    What is Session Tracking?

    HTTP is stateless protocol and it does not maintainthe client state.

    But there exist a mechanism called "Session Tracking"

    which helps the servers to maintain the state to trackthe series of requests from the same user across someperiod of time.

    Different types of Session Tracking?

    a) Cookiesb) URL rewritingc) Hidden form fieldsd) SSL Sessions

  • 8/12/2019 servlets-2

    9/28

    Hidden form fields

    Hidden fields like the above can be inserted in the

    webpages and information can be sent to the server for

    session tracking.

    These fields are not visible directly to the user, but can be

    viewed using view source option from the browsers.

    This type doesnt need any special configuration from the

    browser of server and by default available to use forsession tracking.

    This cannot be used for session tracking when the

    conversation included static resources lik html pages.

  • 8/12/2019 servlets-2

    10/28

    URL Rewriting

    Original URL: http://server:port/servlet/ServletName

    Rewritten URL:

    http://server:port/servlet/ServletName?sessionid=7546

    When a request is made, additional parameter is appended with theurl.

    In general added additional parameter will be sessionid orsometimes the userid.

    It will suffice to track the session. This type of session trackingdoesnt need any special support from the browser.

    Disadvantage is, implementing this type of session tracking istedious.

    We need to keep track of the parameter as a chain link until theconversation completes and also should make sure that, theparameter doesnt clash with other application parameters.

  • 8/12/2019 servlets-2

    11/28

    Cookies

    Cookies are the mostly used technology for session tracking. Cookie is a key value pair of information, sent by the server to the browser.

    This should be saved by the browser in its space in the client computer.

    Whenever the browser sends a request to that server it sends the cookiealong with it.

    Then the server can identify the client using the cookie.

    In java, following is the source code snippet to create a cookie:

    Cookie cookie = new Cookie(sessionID, 7546);response.addCookie(cookie);

    Session tracking is easy to implement and maintain using the cookies. Disadvantage is that, the users can opt to disable cookies using their

    browser preferences.

    In such case, the browser will not save the cookie at client computer andsession tracking fails.

  • 8/12/2019 servlets-2

    12/28

    Session tracking API HttpServletRequest interface has a method to create

    HttpSession object to track the session.

    HttpSession ses = request.getSession(true); this method will check whether already a session is existing

    for the user. If a session is existing, it will return that sessionobject, Otherwise will create a session object expicitly andreturns to the client.

    HttpSession ses = request.getSession();

    Alternate shortcut method for request.getSession(true) HttpSession ses = request.getSession(false);

    this method will check whether a session is existing. If yes,then it returns the reference of that session object, Otherwiseit returns 'null'.

  • 8/12/2019 servlets-2

    13/28

    Creating the session

  • 8/12/2019 servlets-2

    14/28

    Setting a new attribute in session

  • 8/12/2019 servlets-2

    15/28

  • 8/12/2019 servlets-2

    16/28

    ServletContext Scope

    The context scope parameters are shared by all servletsin the same web application

    The context scope parameters are stored in web.xml

  • 8/12/2019 servlets-2

    17/28

    Context scope attributes

  • 8/12/2019 servlets-2

    18/28

    Redirect into another webpage sendRedirect () method:

    This method is declared in HttpServletResponseInterface.

    Signature: void sendRedirect(String url) This method is used to redirect client request to some

    other location for further processing,the new location isavailable on different server or different context.

    Our web container handle this and transfer the requestusing browser ,and this request isvisible in browser as anew request.

    Some time this is also called as client side redirect

  • 8/12/2019 servlets-2

    19/28

    Mechanism used by sendRedirct()

  • 8/12/2019 servlets-2

    20/28

    Using RequestDespacher Forward() method: ( declared in RequestDispatcherInterface ) Signature: forward(ServletRequest request, ServletResponse response) This method is used to pass the request to another resource for further

    processingwithin the same server, another resource could be any servlet,jsp page any kind of file.

    This process is taken care by web container. When we call forward method request is sent to another resourcewithout

    the client being informed,which resource will handle the request it hasbeen mention on requestDispatcher.

    We can get by two ways either using ServletContext or Request. This is also called server side redirect.

    RequestDispatcher rd = request.getRequestDispatcher("pathToResource");rd.forward(request, response);Or

    RequestDispatcher rd =servletContext.getRequestDispatcher("/pathToResource");rd.forward(request, response);

  • 8/12/2019 servlets-2

    21/28

    Forward() sendRedirect()

    request is transfer to other resource

    within the same server.

    request is transfer to another resource to

    different domain or different server

    Web container handle all process

    internally and client or browser is not

    involved.

    container transfers the request to

    browser so url given inside the

    sendRedirect()is visible as a new

    request to the client.We pass request and response object so

    our old request object is present on new

    resource which is going to process our

    request

    old request and response object is lost

    because its treated as new request by

    the browser.

    faster then send redirect. SendRedirect is slower becausecompletely new request is created and

    old request object is lost.

    We can use same data in new resource

    with request.setAttribute () as we have

    request object available.

    We cannot store the request scope data

    because the old request object is lost.

  • 8/12/2019 servlets-2

    22/28

    Example using forward() Using sendRedirect() :

    On same server response.sendRedirect("http://localhost:8090/Chaining/Ch

    ain2");

    On another server String name=request.getParameter("name");

    response.sendRedirect("http://www.google.co.in/#q="+name);

    Using forward() request.getRequestDispatcher(/hello.jsp).forward(req,re

    s)

  • 8/12/2019 servlets-2

    23/28

    Difference between the getRequestDispatcher()

    method of ServletContext and that of ServletRequest

    You can pass a relative path to the getRequestDispatcher() method ofServletRequest but not to the getRequestDispatcher() method ofServletContext.

    For example, request.getRequestDispatcher("../html/copyright.html") is valid, and the

    getRequestDispatcher() method of ServletRequest will evaluate the pathrelative to the path of the request.

    For the getRequestDispatcher() method of ServletContext, the pathparameter cannot be relative and must start with /.

    This makes sense because ServletRequest has a current request path toevaluate the relative path while ServletContext does not.

    You cannot directly forward or include a request to a resource in another webapplication. To do this, you need to get a reference to the Servlet-Context of the other web

    application using this.getServletContext().getContext(uripath). Using this servlet context reference, you can retrieve an appropriate

    RequestDispatcher object as usual.

  • 8/12/2019 servlets-2

    24/28

    Cookies Cookies are text files stored on the client computer and

    they are kept for various information tracking purpose.Java Servlets transparently supports HTTP cookies.

    There are three steps involved in identifying returning

    users: Server script sends a set of cookies to the browser. For

    example name, age, or identification number etc.

    Browser stores this information on local machine for futureuse.

    When next time browser sends any request to web serverthen it sends those cookies information to the server andserver uses that information to identify the user.

  • 8/12/2019 servlets-2

    25/28

    The Anatomy of a Cookie Cookies are usually set in an HTTP header .

    A servlet that sets a cookie might send headers thatlook something like this:

  • 8/12/2019 servlets-2

    26/28

    Setting Cookies with Servlet

  • 8/12/2019 servlets-2

    27/28

    Example :

  • 8/12/2019 servlets-2

    28/28

    Reading Cookies with Servlet To read cookies, you need to create an array of

    javax.servlet.http.Cookieobjects by calling the getCookies( )method of HttpServletRequest. Then cycle through the array, and use getName() and getValue()

    methods to access each cookie and associated value.