Friday, 5 December 2014

JSP life cycle

JSP Life cycle exist in following phases

1. Translation phase
2. Compilation
3. Initialization
4. Instantiation
5. Request processing
6. Destruction

Every Jsp page internally converted to an equalent servlet class. It means writing a jsp page is nothing but indirectly writing a servlet class.
Each jsp page at server side executed in two phases.
                 1. Translation phase
                 2. Service phase/ Request processing phase.
1. Translation Phase
Whenever Web Container is received request, In translation phase  web container creates an equalent servlet class for jsp page and then generates a .class file for that servlet. In this time container creates an Object of the generator .class file and initializes it before executing service phase by calling the jspInit() method.
In Translation phase a container uses two compilers
a) Page compiler -- converts a jsp page to servlet.
b) Java Compiler -- converts servlet .java file to .class file.
The Translation phase is executed for a first request arrived for a jsp page and also for a request given after modification of a jsp page.
 2. Service phase or Request processing phase
After completing Translation phase container call the _jspService() method. In service phase, a request of a client is processed and response for the request will be sent to the client.
Service phase is executed for each request arrived for a jsp page.
after completing the request processing container calls the jspDestroy().

Saturday, 29 November 2014

What is the Different between Struts 1.x and Struts 2.x

Struts 1.x
Struts 2.x
In struts 1.x front controller is ActionServlet
In 2.x front controller is FilterDispatcher
In struts 1.x we have RequestProcessor class
In 2.x we have Interceptors instead RequestProcessor
In struts 1.x we have multiple tag libraries like, html, logic, bean..etc
In 2.x we do not have multiple libraries, instead we have single library which includes all tags
In struts 1.x the configuration file name can be [any name].xml and we used to place in web-inf folder
In 2.x the configuration file must be struts.xml only and this must be in classes folder
In struts 1.x we have form beans and Action classes separately
In 2.x form bean, Action classes are combinedly given as Action class only
In struts 1.x properties file must be configured in struts-config.xml
But in 2.x we need to configure our resource bundle(s) in struts.properties file
In struts 1.x we have programmatic and declarative validations only
In 2.x we have annotations support too along with programmatic and declarative validations

Functional Differences.
In struts 1.x declarative validations are done by using validation frame work
In 2.x, declarative validations are done by using xwork2 frame work by webwork the reason being, its support valuations through Annotations
·         In struts 1.x an Action class is a single ton class, so Action class object is not a thread safe, as a programmer we need to make it as thread safe by applying synchronization
o    In 2.x an Action class object will be created for each request, so it is by default thread safe, so we no need to take care about safety issues here
In struts 1.x we have only jsp as a view technology
In 2.x we have support of multiple view technologies like velocity, Free marker, jasper reports, jsp, etc
In struts 1.x Action class is having servlet dependency, because in execute() method accepts req, res parameter right
In 2.x Action class doesn’t have any servlet dependency, because its execute() method doesn’t accepts any parameters, however we can access all servlet objects with dependency injection 

Friday, 28 November 2014

What is different between optimistic locking and pessimistic locking?


What is the Reflection Api in Java?

Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.

What is Locale Class in Java?

The java.util.Locale class object represents a specific geographical, political, or cultural region. .Following are the important points about Locale:
  • An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to form information for the user.
  • Locale is a mechanism for identifying objects, not a container for the objects themselves.
     
  • For example, the AroundTheWorld program uses three Locale objects: one for the United States, one for France, and one for French Canada. These Locale objects do not contain the population, literacy rate, or any other AroundTheWorld specific data. The application-specific data is contained in resource bundles. The program uses a Locale object to identify what the current locale is and to decide which resource bundle to use to construct its display.  
  •  
  • Class Declaration:
    public final class Locale
       extends Object
          implements Cloneable, Serializable

Saturday, 15 November 2014

Java Program for Given int value to Reverse

import java.util.Scanner;
 
class ReverseNumber
{
   public static void main(String args[])
   {
      int n, reverse = 0;
 
      System.out.println("Enter the number to reverse");
      Scanner in = new Scanner(System.in);
      n = in.nextInt();
 
      while( n != 0 )
      {
          reverse = reverse * 10;
          reverse = reverse + n%10;
          n = n/10;
      }
 
      System.out.println("Reverse of entered number is "+reverse);
   }
}

Friday, 14 November 2014

JAVA Projects - Core Java Spring MVC Hibernate Servlets JSP'S

Servlets, JSP and Oracle Database Simple Login and Registration Example : 

Create the Table : Like Follwing
CREATE TABLE Registeruser(name varchar(25),password varchar(25),email varchar(25),phoneno number(10),address varchar(25));

JSP Pages:
index.jsp

Wednesday, 5 November 2014

Method Overriding with Constructors

In method Overriding If sub class having default constructor then must super class having default constructor otherwise we will get exception. To avoid these problem means we can't write the default constructor in super class then we can write the sub class super() method by passing argument.

 class Main
{
Main(){
System.out.println("i am from super class");
}
Main(int a){
System.out.println("i am from super constructor class");
}

public void m1()
{
System.out.println("i am from Main class");
}
}
public class Meth_ovr extends Main{
Meth_ovr(){
//super(9); If not write the super class constructor
System.out.println("i am from sub contructor");
}

public void m1()
{
System.out.println("i am from sub class");
}
public void m2()
{
System.out.println("i am from m2 class");
}
public static void main(String[] args) {

Meth_ovr m=new Meth_ovr();
m.m1();
//Main mr= new Main();
//mr1.m1();
Main mr1= new Main();
mr1.m1();
}

}

What is differences between functions and procedures in Java?

Sr.No.User Defined FunctionStored Procedure
1 Function must return a value.Stored Procedure may or not return values.
2Will allow only Select statements, it will not allow us to use DML statements.Can have select statements as well as DML statements such as insert, update, delete and so on
3 It will allow only input parameters, doesn't support output parameters.It can have both input and output parameters.
4It will not allow us to use try-catch blocks.For exception handling we can use try catch blocks.
5Transactions are not allowed within functions.Can use transactions within Stored Procedures.
6We can use only table variables, it will not allow using temporary tables.Can use both table variables as well as temporary table in it.
7Stored Procedures can't be called from a function.Stored Procedures can call functions.
8 Functions can be called from a select statement.Procedures can't be called from Select/Where/Having and so on statements. Execute/Exec statement can be used to call/execute Stored Procedure.
9A UDF can be used in join clause as a result set.Procedures can't be used in Join clause

Thursday, 9 October 2014

Spring MVC Flow Diagram



1.      Whenever end user given the request then Spring MVC front controller called Dispatch Servlet will receive the request.
2.      Then Dispatcher Servlet communicate with the HandlerMapping for identifying the suitable controller for given request.
3.      After identifying the suitable controller for the given request HandlerMapping returns the information back to the Dispatcher Servlet.
4 & 5.      Then Dispatcher Servlet dispatches the given request to the controller bean. Controller bean stores the given input in a command class object.
6.      Controller bean calls the business logic implemented in a model.
7 ,8 &9 .      The model can integrate with database and reads or update data.
         Model component returns result back to controller bean.
10.      Controller bean returns model and view object back to Dispatcher Servlet.
11.      Dispatcher servlet communicate the with the view resolver bean and this bean identifies      appropriate view for the given model and view object.
12.  Dispatcher servlet selects the view identified by the view resolver.
            Dispatcher Servlet either forward or redirects the view as a response back to the client.

How to maintain the Session in Servlet?

Session Tracking in Servlets

Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of an user. It is also known as session management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It is shown in the figure given below:
There are four techniques used in Session tracking:
  1. Cookies
  2. Hidden Form Field
  3. URL Rewriting
  4. HttpSession
session tracking

Wednesday, 8 October 2014

Dimond program in Java

import java.util.Scanner;
public class StarDimond {

public static void main(String[] args)
    {
        System.out.print("Enter no of row u want in star pattern : ");
        Scanner in = new Scanner(System.in);
                int num=in.nextInt();
                for(int i=1;i<=num;i++)
                {
                    for(int j=num;j>=i;j--)
                    {
                        System.out.print(" ");
                    }
                   for(int m=1;m<=i;m++)
                    {
                       System.out.print(" *");
                    }
                     System.out.print("\n");
                }
                for(int i=1;i<=num;i++)
                {
                    for(int j=1;j<=i;j++)
                    {
                        System.out.print(" ");
                    }
                   for(int m=num;m>=i;m--)
                    {
                       System.out.print(" *");
                    }
                     System.out.print("\n");
                }  
    }
}
 
Out put:Enter no of row u want in star pattern : 5
      *
     * *
    * * *
   * * * *
  * * * * *
  * * * * *
   * * * *
    * * *
     * *
      *


Wednesday, 1 October 2014

What Session.refresh() method will do in hibernate

Session.refresh() method :  During the bulk update to the DB with hibernate, the changes made are not replicated to the entities stored in the current session. So calling session.refresh will load the modifications to session entities.


Monday, 22 September 2014

What is Garbage Collection

Usually programmer taking very much care while creating the Objects and his neglecting destruction of Useless objects. Due to this neglectance at certain point of time  for the creation of new object sufficient memory may not be available and entire program will be collapse due to memory problems.

But in Java, "as a programmer is responsible only for  creation of objects and he is not responsible for destruction  of useless objects".

Java provided one assistant which is running in the background for destruction of useless Objects. Due to this assistant the chance of failure java program with memory problem i very rare. This assistant is nothing "Garbage Collection".

Hence the main objective of Garbage Collection is to "Destroy useless bojects".

When Garbage Collection is Required?
Programmer is not responsible to destroy useless objects, But It is always a good programming practice to make an object eligible for Garbage collection, if it is no longer required.

An object is said to be eligible for garbage collection , If it is doesn't contain any reference.


Sunday, 21 September 2014

How to Make an Object is eligible for Garbage Collection Explicitly

An object is said to be eligible for Garbage Collection, If it is doesn't contain any reference.
If an object is contain any reference then it is not eligible for Garbage Collection.

If an object is no longer required then assign null to all its reference , then automatically that object eligible for Garbage Collection.

ex:-                Student s1= new Student();
              here Student object is not eligible for Garbage Collection. Because s1 reference is there.
if we assign the null value for the object then that object is eligible for G.C.
           
          ex:-        s1=null;

By Requesting the JVM to Run Garbage Collector:

When ever we are making an object eligible for garbage Collector  it may not be destroyed by G.C immediately when ever jvm runs G.C then only that will be destroyed.

we can request jvm to run garbage collector, programmatically......

1) by System class:
System contain a static method G.C for this
                   System.gc();
2) By Runtime class
by using runtime object  a java application can communicate with jvm.
Runtime class is a singleton class hence we con't create Runtime object by using constructor.
we can create the Runtime object by using factory method getRuntime
                  Runtime r= Runtime.getRuntime();
       

Thursday, 18 September 2014

How many types of Scopes are there in JSP

Scopes in JSP:
4 Types are there:
1.Page
2. Request
3. Session
4. Application

Monday, 15 September 2014

It is possible overloading the main method in java

Yes. It is possible.

public class MainOverloaing {
public static void main(String []args)
{
System.out.println("Hi");
}
public static void main(int... args)
{
System.out.println("hello");
}
}

Output:  Hi

Sunday, 14 September 2014

Palindrome program: Given String is Palindrome or not in java

import java.util.Scanner;

public class TestPolin {

  public static void main(String args[])
  {
     String reverseString="";
     Scanner scanner = new Scanner(System.in);

     System.out.println("Enter a string to check if it is a palindrome:");
     String inputString = scanner.nextLine();

     int length = inputString.length();

     for ( int i = length - 1 ; i >= 0 ; i-- )
        reverseString = reverseString + inputString.charAt(i);

     if (inputString.equals(reverseString))
        System.out.println("Input string is a palindrome.");
     else
        System.out.println("Input string is not a palindrome.");

  }
}



Thursday, 11 September 2014

Java 1.5 new features

  1. Generics for Collections
  2. Enhanced for Loop (for-each loop)
  3. Autoboxing/Unboxing
  4. Typesafe Enums
  5. Varargs/Vargs (Variable-length Argument Lists)
  6. Static Import
  7. Metadata (Annotations)
  8. Formatting
  9. Scanner

Wednesday, 10 September 2014

Autowiring in Spring

Bean wiring means configuring the beans along with its dependencies into on xml.
In bean wiring the programmer is responsible to configure all bean properties into xml file.
In case of auto wiring spring IoC container will automatically wire the dependencies which are in the form of objects. It means auto wiring is supported only for dependency in the form of objects but not primitives and collections.

4 Types of auto wirings are there
1. byName
2. byType
3. Constructor
4. Auto detect.


1)
byName
The byName mode injects the object dependency according to name of the bean. In such case, property name and bean name must be same. It internally calls setter method.
2)
byType
In byType spring container verifies whether a bean class name configured in xml and the property type to be injected are matching or not. If matched then the container injects the class object by calling setter method of the class.
3)
constructor
The constructor mode injects the dependency by calling the constructor of the class. It calls the constructor having large number of parameters.
4)
Auto detect
It is deprecated since Spring 3.