Monday, July 16, 2012

JSP Custom Tag LifeCycle (classical)



1.  Web Container loads the class (class extending TagSupport/ BodyTagSupport class).

2.  Instantiate the class with no-arg constructor

Note : above two steps happens when container sees custom tag first time in JSP page. It might be possible container will use the same object in case of re occurrence of same custom tag.

3.  Container will call the setPageContext(pageContext) method to get the reference of PageContext which will be handed over to Handler class(class extending TagSupport/BodyTagSupport)

4.  If the Tag is nested(invoked from within any other tag) call the setParent(Tag) method.

5.  If the Tag has Attribute, call attribute setter method.

6.  Call the int doStartTag() method which should return either EVAL_BODY_INCLUDE or SKIP_BODY constants.

SKIP_BODY(default) : in this case the tag handler class skips the body of tag and directly call the doEndTag().

EVAL_BODY_INCLUDE : if TLD has mentioned about <body-content> and tag have body than body of the tag will be Evaluated only once before again calling the doAfterBody() method.

7.  If doStartTag() returns EVAL_BODY_INCLUDE than int doAfterBody() will be called and which should return either SKIP_BODY or EVAL_BODY_AGAIN.

SKIP_BODY(default) : doEndTag() method will be called and body will be not evaluated again(as body is already evaluated once due to EVAL_BODY_INCLUDE).

EVAL_BODY_AGAIN : doAfterBody() method will be called again. This is the only method in custom Tag LifeCycle which can be called multiple times.

8.  Call the int doEndTag() method which should return either EVAL_PAGE or SKIP_PAGE.

EVAL_PAGE(default): the remaining JSP Page after the TAG will be evaluated.

SKIP_PAGE : the rest of the JSP page which have this TAG will skipped.   


------------------------------------------------------------------------------------------------------

Directory Structure in ECLIPSE :



-------------------------------------------------------------------------------------------------------------

 Example:

Handler class : ClassicCustomTag.java

package in.ibm;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class ClassicCustomTag extends TagSupport {
    int mCounter=0;
    String Movies[]= {"Dilwale","Taare Zameen Par","Hum"};

    public int doStartTag() throws JspException {
    //    mCounter=0;
        pageContext.setAttribute("movie", Movies[mCounter]);
        mCounter++;
        //return SKIP_BODY;
        return EVAL_BODY_INCLUDE;
    }
      

    public int doAfterBody() throws JspException {
        if(mCounter<Movies.length){
          
        pageContext.setAttribute("movie", Movies[mCounter]);
        mCounter++;
        //return SKIP_BODY;
        return EVAL_BODY_AGAIN;
        }else{
            return SKIP_BODY;
        }
    }
   
   
    public int doEndTag() throws JspException {
        return EVAL_PAGE;
    }
   

}


-------------------------------------------------------------------------------------------------------

JSP Page : ClassicTagTest.jsp 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@taglib uri="/WEB-INF/tlds/ClassicTag.tld" prefix="CTag" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<table border="1">

<CTag:CT>
<tr><td>${movie}</td></tr></CTag:CT>

</table>

I am at the Bottom of the page
</body>
</html>

-----------------------------------------------------------------------------------------------------------=
 TLD File : ClassicTag.tld

<?xml version="1.0" encoding="UTF-8"?>
<taglib>
<jsp-version>1.0</jsp-version>
<tlib-version>1.2</tlib-version>
<uri>ClassicTag</uri>
<tag>
<name>CT</name>
<tag-class>in.ibm.ClassicCustomTag</tag-class>
<body-content>scriptless</body-content>
</tag>
</taglib>
----------------------------------------------------------------------------------------------------------

WEB.XML:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>

  <display-name>ClassicalCustomTags</display-name>
  <welcome-file-list>
   
    <welcome-file>ClassicTagTest.jsp</welcome-file>
  </welcome-file-list>
</web-app>
 
---------------------------------------------------------------------------------------------------------

OUTPUT :





Saturday, July 7, 2012

Struts :ValidatorForm Vs ValidatorActionForm


<><><><><><>
</><><><><><><>
</>

ValidatorForm
ValidatorActionForm
What
Class provided by struts framework for validating form fields
Class provided by struts framework for validating form fields
Why
Instead of manually using basic validation using validate() method in action class, harnesses the rich feature of validation framework( or descriptive validation) provided by the struts using XML Files(Validation-rule.xml & validations.xml)
Instead of manually using basic validation using validate() method in action class, harnesses the rich feature of validation framework( or descriptive validation) provided by the struts using XML Files(Validation-rule.xml & validations.xml)
How
By extending the form class
Ex:
Public class MyForm extends ValidatorForm{
properties & getters setters
By extending the form class
Ex:
Public class MyForm extends ValidatorActionForm{
properties & getters setters
Where
In any web application which is implemented using struts
In any web application which is implemented using struts
Difference
It uses ‘form name’ as identifier to invoke validation
It uses ‘action name’ as identifier to invoke validation
The validations.xml file will be configured as <form-name =”name of the form mentioned in config file related to particular action”>
Ex



Validations.xml
<formset>
<form-name= ”myForm”>
---------------------------
----------------------------
</form-name>

struts-config.xml
<form-beans>
<form-bean  name=”myForm” type=”--------“/>
</form-beans>

<action-mapping>
<action path=”/myFormAction”
name= ”myForm”
type=………          />


The validations.xml file will be configured as <form-name =”action path mentioned in struts-config.xml”>
Ex




Validations.xml
<formset>
<form-name=/myFormAction>
---------------------------
----------------------------
</form-name>

struts-config.xml
<form-beans>
<form-bean  name=”myForm” type=”--------“/>
</form-beans>

<action-mapping>
<action path=”/myFormAction”
name=”myForm”
type=………          />

Benefit
It’s a clear cut way to say that this form has following validations.
Some times it happens that a single form is shared by many actions or JSP pages so to configure a single validation for form would be overkill, we are wasting time by validating all fields which are not related to our page.
A page can be distinguished using ‘Action’ so it is being used here to save us from wastage. 



Complete Example :

Will be posted on 09th July 2012.

Tuesday, July 3, 2012

Servlet Life Cycle


 
Servlet Life Cycle:


When you deploy an application under web-app folder of tomcat home directory and start the tomcat (i.e. deploy the application in tomcat)

1.     Web container (tomcat) reads the Deployment Descriptor (web.xml) and creates a Servlet Context object.  

2.    Container reads the DD and search for <context- param> (if any) and creates a Key/value pair of Strings  for corresponding <param-name> and           
<param-value>.

Ex.  <context-param>
          <param-name>AdminEmail</pram-name>
          <param-value>susheel.nitdgp@gmail.com </param-value>
      </context-param>

Will create a reference with key as ‘AdminEmail’ and value as ‘susheel.nitdgp@gmail.com’

3.    This key/ value reference is provided to ServletContext reference.

4.    ServletContextListener (if any) will be called.

5.    Container will create ServletConfig Object.

6.    Container reads the DD and search for any servlet initialization parameters.

Ex. <servlet>
          <servlet-name>……..</servlet-name>
          <servlet-class>………</servlet-class>
          <init-param>
                   <param-name>…….</param-name>
                   <param-value>……..</param-value>
          </init-param>
     </servlet>

7.    The key value pair of Strings will be created for init parameters (same as for context param) and will be assigned to ServletConfig reference.

Note : no servlet is still created till this step even servlet life cycle is not started.

8.    Container will create request and response objects.

9.    Servlet class will be loaded by container.

10.   Servlet default no-arg constructor will be called and a simple java object is created(still we don’t have servlet object).

11.  First Life Cycle method for Servlet init(ServletConfig ) will be called and servlet object will be created and initialized.

12.  Container will start a thread and calls the Second life cycle method and most used method service(request, response) of the Servlet.

13. Service() method will call doGet(request, response) or doPost(request, response) method based on the submitted method name.

14.  Service() method is the place where all the work is done.

15.   An response is created by using getWriter() or getOutputStream() methods of Response object.

16.  Response is sent to any other servlet, jsp using Request Dispatcher or committed to client.

17.  In later case request, response objects will be destroyed and thread will be destroyed or sent back to connection pool managed by container.

Sunday, July 1, 2012

Java Interface Rules with Program

package in.ibm;

public class InterfaceRules {
   
//    Inter6 ref1 = new Inter6();    Error :  no constructor allowed for Interface

            // Object creation is not possible in Interface
   
    Inter6 ref;

   // We can create the ref of Interface but cannot create the objects as it is fully abstract class
   
    public static void main(String [] str){
       
    System.out.println(inter7.AB);
    System.out.println(inter8.BC);
    System.out.println(inter9.CA);
   
    new Test2().display();
    }
}

class A{}

interface inter1 {}

interface inter2 extends inter1 {}                 // allowed as interface can extend another interface

interface inter3 extends inter1,inter2 {}                  // allowed as interface allow multiple inheritance

//interface inter4 implements inter1{} // ERROR: as Interface only extend the interface can't implement it

//interface inter5 extends A{} // ERROR : class cannot be the super Interface for a interface

class B extends A implements inter1, inter2{}  // Allowed as class can implement multiple interface but can extend one and only one class

//class C extends A,B implements inter1, inter2,inter3{} // ERROR : as class tries to extend more than one class

interface Inter6{
       
//    inter6(){}         //ERROR: interface doesn't have any constuctor, NO NEED as interface doesn't have any instance member so what is the use of constructor
   
//    {}                 // ERROR : if no object is going to be created for interface do you see any use of object initialization block

//    static     { }     // as for the interface class is not going to be loaded so no need of static block as it will run only once when class is loaded
   
//    int AB;             // ERROR : by default var declared inside interface have signature public static final i.e.
               
// Var is not an instance variable and value is fixed so Compiler will not load class to instantiate the var as it is CONSTANT
   
    int AB=20;     // allowed as we are giving a value to final variable
   
    //void display(){}; ERROR: // by default member of interface is public abstract and Abstract can't have body
   
    int calculate(int a, int b); // Allowed as we are not specifying any body.

    // Method declared is instance member of the interface to access that you require some object that's why without inheriting we cannot

 //access the interface methods while member variables are by default static so no need of instances we can call them directly or with

    //interface name
   
    void display();
   
}


//class Test implements Inter6{}

 // ERROR : Class implementing any interface must implement all the methods of interface

abstract class Test implements Inter6{}

 // allowed as class is declared abstarct, any subclass of TEST have to implement the methods

class Test1 implements Inter6{

   
    //public float calculate(int a, int b) { }

//ERROR: As we are violating the overriding rules that return type should be same for overriden methods
   
    public int calculate(int a, int b) {
        return a+b;
    }

   
    public void display() {
            System.out.println ("Dispaly the result +" + calculate(5,10));
    }
   
}


interface inter7 {
    int AB=10;
    void display();
}

interface inter8 {
    int BC=20;
    int AB =30;

 // going to give ambigiuity in thr class which will implement both inter7 & inter8 as by inheritance rule only one copy od duplicate code shold go to

 // subclass and here we are sending 2 copies of AB to Test2
    void display();
}

 // allowed as interface can extend another interface

interface inter9 {
    int CA=30;
    void display();
}            


class Test2 implements inter7,inter8,inter9{

    //    void display(){ } // ERROR as here visibility is 'default' which is restrictive than by default visibility of methods of interfaces(public)
       
    public void displayValues(){

//        System.out.println(AB); // ambiguity Error

        System.out.println(inter7.AB);
        System.out.println(inter8.AB);
        System.out.println(BC);

        System.out.println(CA);   // no ambiguity so no error
    }

    public void display() {
        System.out.println("display methods inherited from all Interfaces");
       
    }
}