Tuesday, 6 August 2013

How can we perform Exception Handling in JSP?

Exception handling can be performed in JSP with three ways
  1. Using page directive (isErrorPage=”True” and errorPage=”error.jsp”).
  2. Using simple Try/catch  
  3. Using JSTL

  1.  Page Directive Exception Handling: - This is the most common way of JSP exception handling. In this approach, we use the errorPage and isErrorPage methods of page directive. As in the below example, we used two JSP pages.
·         generateException.jsp
·         error.jsp
The generateException page used the errorPage method of page directive for describing the name of the page which will handle the exceptions occurred in the page (As error.jsp in below example). Now when any exception will occur in the generateException page, it will go to the error.jsp page.
              In error.jsp page we used the isErrorPage method of the page directive to tell the container that this page is for exception handling and then container will give an implicit object “Exception” for handling the exceptions. This can be easily understood with the below example.
generateException.jsp
<%@ page errorPage="error.jsp" %>
<%
  int count=0;
  count=100/count;

%>

error.jsp
<html>
<body>
<%@ page isErrorPage="true" %>
<%="Sorry, Exception occured"%>
</br>
<%="Here is your Exception:- "+exception%>
</body>
</html>


2.  Try/Catch Block exception handling: - This is very much similar to the core java exception handling. We put the code under the try block and catch the exception in exception block.
This can be easily understood with the example below.

generateException.jsp
<%
 try
  {
     int count=0;
     count=100/count;
  }
catch(Exception e)
  {
                out.println("Try/Catch block Exception Handling "+e);
  }

%>

3.       JSTL Exception: - JSTL (Java standard tag library) is used for making coding easy. JSTL gives some standard tags to perform some specific tasks so JSTL also provide tags to perform exception handling. Please refer the below example for JSTL exception handling.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
 <body>
    <c:catch var="ExceptionVar">
    <% int count=0;
     count=100/count; %>
    </c:catch>
    Test :
                <c:if test = "${ExceptionVar != null}">
                out.println("Try/Catch block Exception Handling ");
                ${ExceptionVar}
    </c:if>
    </body>
</html>

Wednesday, 24 July 2013

What is Comparator and Comparable interface in java and what are the differences between them?



The Array.sort() and Collections.sort() can sort array and arraylist on the basis of single values but Lists are meant to store objects and they can have multiple properties so if need to sort list on the basis of some other properties than we need to use Comparable and Comparator interfaces.

Basically, Collections.sort()  have two types in java collection framework .
  1. Collections.sort(List of objects of class which implements Comparable   or list of objects);
  2. Collections.sort(list of objects, object of class implementing Comparator);

Comparable Interface: When we use Collection.sort() with single arguments or first type of Collections.sort then it basically needs the object of the class and the class should implement Comparable interface of Java.lang package.Comparable interface of java has an abstract method compareTo(Class object) which need to be implemented every time the class implements the Comparable interface. This method is containing the logic for sorting the list on the basis of some property. It compares the property with object property and returns the integer type result as:
Positive    – this object is greater than object’s property
Zero          – Both properties are equal
Negative – this object is less than object’s property

Let‘s suppose that we have a class containing the employee data(Emp Name, Emp Age). Now we can sort the list on the basis of name as well as age with the help of Comparator (refer below example).

 import java.util.*;

class empData implements Comparable<empData>
{
    String name="";
    int age=0;
    empData()    {    }
    empData(String name, int age)  {
          this.name= name;
          this.age=age;
      }

     public int compareTo(empData obj)    {
         // return this.age - obj.age;   /*If we uncomment this line and comment the line below it will sort  
                                                                the list on the basis of employee name*/
         return this.name.compareTo(obj.name); //This will sort the list on the basis of employee age
         }
 }
     
public class demoComparable
      {
        public static void main(String s[])      {
          List<empData> list = new ArrayList<empData>();
          list.add(new empData("B",50));
          list.add(new empData("A",30));
           list.add(new empData("e",25));
            list.add(new empData("c",45));
             list.add(new empData("d",52));
          System.out.println("List before sorting");
          for(empData a : list)  {

                System.out.print(a.name+"  ");
                System.out.println(a.age);   }

/*Calling the sort by passing the list of empData Class objects which implements Comparable interface */
Collections.sort(list); 
          System.out.println("List after sorting");
          for(empData a : list)
          {
                System.out.print(a.name+"  ");
                System.out.println(a.age); }}}
      
Comparator Interface: When we use Collection.sort() with two arguments or second type of Collections.sort then it basically needs the object of the class and the class should implement Comparator interface of Java.util  package. Comparable interface of java has an abstract method compare(Class object 1,class object2) which need to be implemented every time the class implements the Comparator interface. This method is containing the logic for sorting the list on the basis of some property. It compares the object2 property with object1 property and returns the integer type result as:
Positive    – Object1 property is greater than object 2 property
Zero          – Both properties are equal
Negative – Object1 property is less than object 2 property

Same above example can be recreated as below example to understand the concept of Cmparator sorting.

import java.util.*;

class empData implements Comparator<empData>
{
    String name="";
    int age=0;
    empData()    {    }
    empData(String name, int age)  {
          this.name= name;
          this.age=age;
      }

     public int compare(empData a, empData b){
         // return a.age - b.age;   /*If we uncomment this line and comment the line below it will sort  
                                                                the list on the basis of employee name*/
         return a.name.compareTo(b.name); //This will sort the list on the basis of employee age
         }
 }
     
public class demoComparator
      {
        public static void main(String s[])      {
          List<empData> list = new ArrayList<empData>();
          list.add(new empData("B",50));
          list.add(new empData("A",30));
           list.add(new empData("e",25));
            list.add(new empData("c",45));
             list.add(new empData("d",52));
          System.out.println("List before sorting");
          for(empData a : list)  {

                System.out.print(a.name+"  ");
                System.out.println(a.age);   }

/*Calling the sort by passing the list of empData Class objects  and object of the class which implement the comparator(it can be same class whose properties need to be sort or any other class implementing the comparator interface)*/
Collections.sort(list,new empData());
          System.out.println("List after sorting");
          for(empData a : list)
          {
                System.out.print(a.name+"  ");
                System.out.println(a.age); }}}


Differences between Comparator and Comparable

S.No.
Comparable
Comparator
1
Comparable comes under JAVA.LANG Package
Comparator comes under JAVA.UTIL Package
2
It has an abstract method compareTo(class type variable)
It has an abstract method compare(class type variable1 ,class type variable2)
3
The class whose properties need to be sort must implement Comparable interface that’s why they provide natural ordering
The class whose properties need to be sort may or may not implement Comparator interface. Some other class can have the sorting logic or can implement Comparator interface.
4
It is called when Collections.sort(list) is called
It is called when Collections.sort(list, comparator) is called