Monday, 7 September 2015

User Defined Tags

User Defined tags:

·         All predefined tags are sufficient to remove java code from jsp. So java people released Tag class which is used to created user defined tags
·         Custom tags are collection of user defined tags
·         Procedure to develop User defined tags
o   Identify all tags
§  Add
§  Sub
§  Mul
§  Div
§  Mod
o   Identify tag library name
§  Arithmetic
o   Develop tag handler class
§  This is a class which can use the Tag interface or TagSupport implementation class.
§  We need to implement the doEndTag() to provide the functionality of a tag
§  It will return the integer value (EVIL_PAGE,SKIP_BODY)
§  EVIL_PAGE ----> JSP will execute the remaining part as well
§  SKIP_BODY-----> JSP will skip the remaining body of page
public class AddTH extends TagSupport {
      int one;
      int two;
      public void setOne(int one) {
            this.one = one;
            System.out.println(one);
      }
     
      public void setTwo(int two) {
            this.two = two;
            System.out.println(two);
      }

      public int doEndTag() throws JspException {
            try {
                  JspWriter out = pageContext.getOut();
                  out.print((one+two));
            }catch(IOException e) {
                  System.out.println(e.getMessage());
            }
            return EVAL_PAGE;
      }
}

o   Develop tld file
§  This is a configuration file to specify the tag name as well as java class
§  We need to place in WEB-INF folder
<taglib>
      <tlib-version>1.0</tlib-version>
      <jsp-version>1.2</jsp-version>
      <short-name>arth</short-name>
      <uri>http://www.arth.com/tags/</uri>
      <tag>
            <name>add</name>
            <tag-class>com.ibm.taghandlers.AddTH</tag-class>
            <attribute>
                  <name>one</name>
                  <required>true</required>
            </attribute>
            <attribute>
                  <name>two</name>
                  <required>true</required>
            </attribute>
      </tag>
</taglib>

o   Configure tld in web.xml
  <jsp-config>
    <taglib>
      <taglib-uri>http://www.arth.com/tags/</taglib-uri>
      <taglib-location>/WEB-INF/Arth.tld</taglib-location>
    </taglib>
  </jsp-config>

o   Jsp to use those tags
<%@ taglib uri="http://www.arth.com/tags/" prefix="arth"%>
<arth:add two="10" one="20"></tag:add>

·         Internal process for above class
o   When we use arth:add jsp compiler check the prefix of a tag(arth)
o   JSPC checks the tag lib is configured with this prefix
o   If not configured JSPC will treat it as a template text and display on browser
o   If configured JSPC check for the uri(http://www.arth.com/tags/) and looks into the web.xml file for this with <taglib-uri>
o   Then JSPC checks the tld file for specific uri and opens it check for the tag name(add)


o   JSPC execute the class and return the output to browser. Based on return value JSPC execute the remaining page

Filters

Filters:

·         Filter is a java program which provide the implementation of filter interface directly or indirectly
·         Filter is an object that performs the filtering tasks on either the request to a resource or response to resource.
·         Examples that have been identified for this design are
1) Authentication Filters
2) Logging and Auditing Filters
3) Image conversion Filters
4) Data compression Filters
5) Encryption Filters
6) Tokenizing Filters
7) Filters that trigger resource access events
8) XSL/T filters
9) Mime-type chain Filter 
·         Filter contains the following methods
o   init(FilterConfig config)
o   doFilter(ServletRequest request, ServletResponse response,    FilterChain chain)
o   destroy()
·         Procedure to create first application
o   Develop dynamic web module
o   Create filter class
public class MyFirstFilter implements Filter{
      FilterConfig config;
     
      public void init(FilterConfig config)     {
            this.config = config;
            System.out.println("init");
      }
     
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            HttpServletRequest requ = (HttpServletRequest)request;
            ServletContext application = requ.getServletContext();
            application.log("" + requ.getRemotePort());
            Enumeration<String> enu = requ.getHeaderNames();
            while (enu.hasMoreElements())       {
                  String s = enu.nextElement();
                  application.log(requ.getHeader(s));
            }
            chain.doFilter(request, response);
      }
     
      public void destroy()   {
            System.out.println("Destroy");
      }
}

o   Configure filter in web.xml file
<filter>
    <filter-name>firstFilter</filter-name>
    <filter-class>com.ibm.filter.MyFirstFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>firstFilter</filter-name>
    <url-pattern>*</url-pattern>
  </filter-mapping>

o   Deploy application
o   Access page from browser
·         Every request need to go to the filter so filters are import role in webapplications
·         Logging filter
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
                HttpServletRequest requ = (HttpServletRequest)request;
                ServletContext application = requ.getServletContext();
                application.log("" + requ.getRemotePort());
                Enumeration<String> enu = requ.getHeaderNames();
                while (enu.hasMoreElements()){
                                                String s = enu.nextElement();
                                                application.log(requ.getHeader(s));
                }
                chain.doFilter(request, response);
}


Friday, 28 August 2015

JSF

1      JSF:

1.1    Lifecycle:

Lifecycle has 6 phases. These phases involved based on the request.
1.       Restore view
2.       Apply Request values
3.       Process validations
4.       Update model values
5.       Invoke application
6.       Render response

1.1.1    Restore View:

This is the first phase and used to construct the view to display in the front end. Every view has its own view id and stores inside the FacesContext session object. JSF view is a collection of components associated with its current status. This is having two state saving mechanisms. Those are
·         Server (Default). The state of each view will be stored inside the server.
·         Client. The state will stored inside the hidden variables of browser.
These values will be configured inside the web.xml file and following is the code to configure this data.
<context-param>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
</context-param>

JSF controller uses the view id to look up components for the current view. If it doesn’t exist JSF creates new view. If it exists it will use the same view. View contains all the GUI components.
The phase of lifecycle presents three view instances.
·         New view:
o   In this case JSF builds the view of faces page and wires event handlers and validators to the components
·         Initial view
·         postback
FacesContext contains all state information JSF needed and this will store inside request or current session. FacesContext stores view in its view root property that means view root contains all JSF components for the current view id.

1.1.2    Apply request values:

After component is created/restored each component in component uses decode method to extract new values from request parameter and if the conversion fails jsf send that to render response phase.
This phase is applied only on action submissions. If we did not submit any actions in this phase only first and last phases will be executed.
<h:inputText binding="#{myBean.inputComponent}"
            value="#{myBean.inputValue}"
            valueChangeListener="#{myBean.inputChanged}"
            immediate="true" />
If we apply immediate=”true” as shown in above code JSF will execute validators and converts on this phase only after that JSF skips the validators on process validations phase. If no immediate=”true” system will execute validations on process validations phase.

1.1.3    Process validations:

All validations and converters are applied here. Suppose if we have following tags to html page it will perform validations in this phase.
<h:inputText binding="#{myBean.inputComponent}"
            value="#{myBean.inputValue}"
            valueChangeListener="#{myBean.inputChanged}">
      <f:converter converterId="converter" />
      <f:validator validatorId="validator" />
</h:inputText>
<converter>
    <converter-id>converter</converter-id>
    <converter-class>com.chandra.jsf.MyConverter</converter-class>
</converter>
<validator>
   <validator-id>validator</validator-id>
   <validator-class>com.chandra.jsf.MyValidator</validator-class>
</validator>
Any validations fails on above page system will send response directly to render response phase and displays the error message to the user.
If we apply the immediate =”true” to the input fields system will apply all validations on the apply request value phase only nothing will happen in this pahse.

1.1.4    Update model values:

In this phase all values will be applied to the backing beans and data can be accessed after this phase on backing beans.
public class Bean {
      private Integer id;
      public Integer getId() {
            return id;
      }
      public void setId(Integer id) {
            System.out.println(id);
            this.id = id;
      }
      public String submit() {
            System.out.println("ID value:" + id);
            return "";
      }

}
Bold code well be executed in Phase 4. All previous phases will be applied only one server side.
If we apply immediate=”true”. This phase is also skipped

1.1.5    Invoke application:

Main action will be performed in this phase.

1.1.6    Render response:

Phase construction begins here again.

1.2    Phase Listener class:

This class executes when phase is initialized. We have two methods beforePhase and afterPhase.
public class MyPhaseListener implements PhaseListener {

      private static final long serialVersionUID = -8180590158099109675L;

      public PhaseId getPhaseId() {
            return PhaseId.ANY_PHASE;
      }

      public void beforePhase(PhaseEvent event) {
            System.out.println("START PHASE " + event.getPhaseId());
            System.out.println("Before Phase");
            pahseDetialsPrint(event, '#');
      }

      public void afterPhase(PhaseEvent event) {
            System.out.println("END PHASE " + event.getPhaseId());
            System.out.println("After Phase");
            pahseDetialsPrint(event, '*');
      }

      public void pahseDetialsPrint(PhaseEvent event, char specialCharacter) {
            // findRequestValues(event, specialCharacter);
            // findComponentValues(event);
      }

      public void findComponentValues(PhaseEvent event) {
            List<UIComponent> list = event.getFacesContext().getViewRoot()
                        .getChildren();
            for (UIComponent component : list) {
                  for (UIComponent childComponent : component.getChildren()) {
                        if (childComponent instanceof HtmlInputText) {
                              HtmlInputText text = (HtmlInputText) childComponent;
                              System.out.println(text.getValue());
                        }
                  }
            }
      }

      public void findRequestValues(PhaseEvent event, char specialCharacter) {
            HttpServletRequest request = (HttpServletRequest) event
                        .getFacesContext().getExternalContext().getRequest();
            Map<String, String[]> map = request.getParameterMap();
            for (int i = 0; i < 20; i++) {
                  System.out.print(specialCharacter);
            }
            System.out.println();
            for (String s : map.keySet()) {
                  System.out.println("Key:" + s);
                  for (String val : map.get(s)) {
                        System.out.println("Vlaues:");
                        System.out.println(val);
                  }
            }
            System.out.println();
      }
}

1.3    Login Form:

To design login form

1.3.1    Managed Bean:


1.3.2    Navigation:


1.4    Resource bundle:


1.5    Basic tags:


1.6    Facelets tags:


1.7    Converter class:


1.7.1    Convert Number:


1.7.2    Convert date time:


1.8    Validator class:


1.8.1    Validate Length:


1.8.2    Validate Required:


1.8.3    Validate Regular expression:


1.9    Data table creation:


1.9.1    Add row:


1.9.2    Delete row:


1.9.3    Sorting:


1.9.4    Display row numbers:


1.9.5    Repeat tag:


1.10   Event Handlers:


1.11   Hibernate Integration:


1.12   Spring Integration: