Tuesday, December 21, 2010

JSP- II

Expression Language:
          Expression Language is official from JSP 2.0. EL is used to do most of the thing what we did using Expression and declaration.
          Java in JSP impends, designers to know Java and Java in JSP is hard to maintain and change. For these reasons EL was required. EL isn't the replacement of java functionalities used in JSP pages. It is the convenient way to invoke java code. Plain old java methods are created somewhere else and calling using EL. EL always enclosed in curly braces, prefixed with $ like ${el}.
           With inclusion of EL, there is no need for scriplets in the pages. Even if there are some scriplets written, it can be easily ignored. Earlier this was done in the directive tags. Now it was done only at web.xml file.  
      <scripting-invalid>true</scripting-invalid> in jsp-config tag.
In the same way. EL can also be ignored in a page. But EL was enabled by default.
      <el-ignored>true</el-ignored> in jsp-config tag.



Monday, December 13, 2010

Java Servlet Pages - I

               JSP.. Java Server Pages is like other CGI scripting files which has HTML and scripting language specific code. Container transform JSP code into java source code and compiled into java servlet class. JSP is like that of other servlet class except that, it was written by the container.

JSP -> Servlet:
               JSP file was converted into a java servlet with name matching the jsp file. A service method was created with HTTP request and response as arguments. This service method will throw exceptions related to its operations. JSP file has as many as tags. Each tags are processed and corresponding servlet code was generated. Some of the processing are:
Directives are made as import
HTML tags are printed using out.write
Declarative tags are initialized
Expression tags are printed using print.
More information about these tags comes now....

Scriptlet:
               Scriptlet is the basic tag that takes any java code inside it.
Scriplet tag ~ <% ..... %>
A small variation in Open Scriptlet tag conveys different meaning to the container.

Directive
               Directive instructs container a special meaning other than poj. Directives are usually added at the beginning of the jsp file.
Directive tag ~ <%@ . 
Three ways Directive can be used:
  1. Page
  2. Include
  3. Taglib
               Each type is identified by the their name like <%@ page... %>, <%@ include... %> and <%@ taglib... %>.
These are like HTML tag attributes. Important thing is that there should not be any semi-colon in these tags.
    Page:
                   This directive specifies the package to be imported for this jsp file. Syntax will be of following patterns
    • <%@ page import="Lib.foo" %> ~ to import single class in a package.
    • <%@ page import="Lib.*" %> ~ to import all classes in a package.
    • <%@ page import="Lib.*, java.util.*" %> ~ to import classes from more than onepackage.
    Include:
    <releasing soon>
    Taglib:
    <releasing soon>

    Expression:
                   Expression is another tag type supported by JSP. Its like a printer, whatever you put inside gets printed. There is no need to put print statement to display it in pages.
    Expression tag ~ <%= ...... %>
    Statement inside the expression tag should not have a semi-colon. But why? Here it is, whatever inside the expression tag is treated as argument for print function. Putting semi-colon at the end means putting the semi-colon at the end of argument in the function call within "()".

    Declaration:
                   A variable can be declared in scriptlet and can be used in other tags. But each time when the service method 
    Declaration is a tag type inside which method and variable can be declared. These are static by nature i.e. whatever declared inside this declaration tag, gets printed outside the service class in the generated servlet.
    Declaration tag ~ <%! %>


    3 Methods:
                   The process and stages involved in converting a JSP file to servlet file need not to be known, except the interface that will be implemented by the servlet class and teh 3 methods.
    jspInit():
    This method is called from init() method. This can be overridden.
    jspDestroy():
    This method is called from destroy() method. This can be overridden.
    _jspService()
    This method is called from servlet's service method.  This makes a new thread for each  request and response. This methods cannot be overloaded or overridden


    Translation & Compilation:
                   This translation and compilation of JSP pages to servlet will take place only once for a page. It happens during the first client request. This process can even made before first client request. But it depends on the vendor who supports the feature. A query string "?jsp_precompile" when append on a jsp, the container translate and compile the file even without waiting for the first client request.

    Accessing Context parameters:
    Configuration in web.xml:
                   Initialising parameters for the page can be specified the same way as like that of a servlet. In addition to servlet mapping in web.xml, <jsp-file>xyz.jsp</jsp-file> tag should be added inside corresponding <servlet> tag.
    Overriding init method:
                   Method that initialises init parameters should be created in the name "jspInit". "jspInit" function should be created inside the declaration tag. This function will be called from init method of the translated servlet. Servlet context parameters are fetched and set to as attributes.
    Accessing Attributes:
                   In JSP, there is nothing called as context scoped. Even though attributes in application scope are bound to servlet context object. The attributes set in jspInit method can be accessed thur application.getAttribute("attribute name");

    Attribute Scope:
                   Servlets have only 3 attribute scope (context) .i.e Application. Request and Session.  JSP have one additional attribute scope i.e Page scope. With this page context reference, any other scoped attributes can be accessed. Access in the sense to get and set. 
                   The getAttribute and setAttribute methods of pageContext comes in two forms (overloaded). The overloaded methods takes one additional int argument. This int argument is to specify the context type.
    pageContext.getAttribute("foo", PageContext.SESSION_SCOPE)
    pageContext.getAttribute("foo", PageContext.APPLICATION_SCOPE)
    pageContext.setAttribute("foo", "asdf" ,PageContext.SESSION_SCOPE)
    pageContext.setAttribute("foo", "asdfsadfasfa",  PageContext.APPLICATION_SCOPE)

    Servlet

    Servlet:
    Servlets are protocols, platform independent server side component written in java language. Servlets can be used in any servlet enabled servers. It dynamically extend with java enabled servers.
    Primitive use of servlets is to serve HTTP request-response paradigm.

    As servlets run on server, they do not require GUI. Servlets are the server side counterparts of applets (Which runs on client).


    Sequence of Operation:

    • Container creates a request and response object.
    • Container creates a new thread and calls the service method of the servlet with the request and response objects.
    • The service method calls the method corresponds to the HTTP request type (POST. GET).
    • Servlet send the response to the client with the response object.
    • Request and Response object loses their scope. They are destroyed or ready for garbage collection.
    For each request container does not create new instance for a servlet. For each request, container assigns new thread to the same instance of the servlet.

    Life Cycle of Servlet:
    • Container loads the servlet class.
    • Container creates instance of the class. Servlets no-arg constructor is being called. So constructor cannot be re-written.
    • init() method is called. This can be overridden for various parameter initialisation and connectivity ..etc.,
    • Once initialized, servlet is ready to serve (service method doPost, doGet .., etc) client request.
    • Servlet gets destroyed.
    Container loads the servlet classes when the web-app is started or when the first client requests. Container gives choice to choose the mode. Even when it loads the servlet when the web-app loads, it will not service method will not run till it was initialised.

      Monday, December 6, 2010

      Session & cookie

      Identifying Client:
               In web pages where a particular set of process has to be carried out, the client has to be identified by the container (server). Being a stateless transfer protocol, HTTP does not store the state of client. In other words, does not remember the client to which it respond previously. The container does not know that it was the same client which requested before. Each request will be considered as a new request.

      Trump Card:
               The trump card for the problem is the "session", which is responsible for identifying a client by the container. Session is used by container to identify the client as , it was the previous one i was responded

                Container identifies each client by assigning a unique session id. This session id was exchanged between client and container. . Container has to informed to do so when required. Of all the methods available to exchange session id between client and container, using cookie was the simplest and common method. Once a cookie is set, it will automatically exchanged between client and container unless client ignores storing cookie.

      Cookie:
                Cookie is a small piece of date represented as a name:value; string. Cookie was transmitted between client and server. Client need not do anything to establish or manage cookie. For each request made from the client it was done automatically. Usually, once the client was closed, the cookie will be destroyed. But it can be set to remember if client has such provisions.
                Sending cookie and header in the response are both different deals. For sending header name value pairs are passed like response.addHeader("name", value);. But for sending cookie, the cookie object was sent instead like response.addCookie(cookieObject);

       How Container manage cookie?
      • Creates cookie object
      • Creates session id
      • Stuff session id into cookie object
      • Set cookie as a part of response
      • Identifies and matches the cookie value in further requests.


      HTTP Session Methods:
      • getCreationTime()
      • getLastAccessedTime()
      • setMaxInactiveInterval()
      • getMaxInactiveInterval()
      • invalidate()
      Three ways the session can be destroyed:
      • After the specified session expiry time
      • After the call of invalidate() function
      • After the web-application goes down
                Session time out duration can be set in DD. Parameter is specified in-terms of minutes.
                If time-out value of any one session has to be modified, they modify that particular session alone using the syntax
      setMaxInactiveInterval(mins * 60);
      Note: Here it is specified in seconds.
      setting setMaxInactiveInterval as 0 is equivalent to calling invalidate() on that particular session.

      Session Life Cycle Events:
                A session undergoes various milestone during its life cycle. During each stage it pass through events and its corresponding milestones.
      Milestone: Life Cycle i.e. Session Created or Destroyed
      Event: HttpSessionEvent
      Listener:HttpSessionListener

      Milestone: Attributes i.e. when an attribute is added, removed & replaced
      Event: HttpSessionBindingEvent
      Listener: HttpSessionAttributeListener

      Milestone: Migration i.e. when a session is about to passivated or activated

      Event: HttpSessionEvent
      Listener: HttpSessionActivationListener