Monday, July 18, 2011

Request Dispatching -- Java

Methods of Request Dispatcher :

1. public void forward(ServletRequest req,ServletResponse resp) throws ServletException,IOException2.

publpublic void include(ServletRequest req,ServletResponse resp) throws ServletException,IOException

Forward mechanism:

If the Servlet – 1 is responsible for preliminary processing and Servlet –2 is responsible to provide complete response to the end user then we should go for forward mechanism. While performing forward , new response object will be created and handed over to the Servlet --2. Hence if any response that is added by the Servlet —1 will not be delivered to the end user. Only the response generated by the Servlet – 2 will be delivered to the end user. Servlet – 2 can also change the response headers which are already set by the Servlet – 1. In the forward mechanism the same request object will be forwarded to the second servlet.. Hence in the form of request scoped attributes information sharing is possible between the components.

When using forward() , the control comes back to the Servlet –1 to finish the execution of remaining statements. After this only the Servlet – 2 will display the response to the end user. In the remaining statements if we are trying to write anything to the response those statements will be ignored by the web container. If any exception is raised then the exception indormation is displayed to the end user instead of Servlet –2 respone. In a servlet we can call forward() only once and mostly as the last statement.




Difference between Forward and sendRedirect

Forward:

Since forward() method of RequestDispatcher is handled on the server ,
therefore the request and its associated session are available to the forwarded
resource and you can pass data between them using request.setAttribute().
forward()separates the responsibilities for handling the requests among several
components. This method generally sends a request and response object to
resources (servlets or JSP's) of the same ServletContext. You can also decide to
forward to one page in one condition and a different page in another. RequestDispatcher
transfers control immediately whenever the forward() method is called to the resource
referenced by the RequestDispatcher.A forward is performed internally by the container
the browser is completely unaware that it has taken place, so its original URL remains
intact and any browser reload of the resulting page will simply repeat the original request,
with the original URL. When the forward is done, the original request and response objects are
transfered along with additional parameters if needed.


sendRedirect

The transfer of control is delegated to the browser by the container. That is, the redirect
sends a header back to the browser / client. This header contains the resource url to be
redirected by the browser. Then the browser initiates a new request to the given url. Since
it is a new request, the old request and response object is lost. It is like keying in a new
URL in the browser. A sendRedirect() also updates the browser history and transfers control
only when the whole service method completes. There is only one way to pass data is through the
session or using web parameters.RequestDispatcher.forward() and PageContext.forward() are effectively
the same. PageContext.forward is a helper method that calls the RequestDispatcher method.
When you invoke RequestDispatcher.include(), the servlet engine transfers control of this HTTP request
internally from your current servlet or JSP to another servlet or JSP or static file, while invoking
response.sendRedirect() method sends an HTTP response to the browser to make another request at a different URL.
 
Aredirect is a two step process, where the web application instructs the browser to fetch a second URL, which
differs from the original. A browser reload of the second URL will not repeat the original request, but will
rather fetch the second URL.Redirect is slower than a forward, since it requires two browser requests, not one .
Objects placed in the original request scope are not available to the second request
 
For example, sendRedirect can transfer control from http://javapapers.com to http://anydomain.com but forward
cannot do this.
 
‘session’ is not lost in both forward and redirect.
To identify difference between forward and sendRedirect keep an eye on the address bar of your browser, in forward, you will not see the forwarded address in redirect, you can see the redirected address.

Finally in java : case

public class FinallyExample1 {

public static void main(String[] args) {
System.out.println((new FinallyExample1 ()).test());
}

public int test() {
try {
return 1;
} finally {
return 0;
}
}
}

'Finally' can be written to override the return values.

Difference between Array and Arraylist.

Array is an object and it stores the object of same type
Eg : It stores complete integer types or string types
         int[] MyIntArray = new int[3];
string[] MyStringArray = new MyStringArray[2];
Arraylist is a collection in which we can store objects of any data type.
     Eg : Arraylist al = new Arraylist()
al.Add(13); // Integer Type
al.Add(10); // String Type
2. Arrays have Fixed Length whereas Arraylist varies in leghth as the objects are Added. 
 
In Java an Array is always of fixed size. The size has to be defined at the initializing time of the array. The number of the rows is a must for any array, though the number of columns may be specified later. By using Array, there is comparatively less flexibility, as the size need to be known before hand. And if you initialize an array that is too long, then it results in wastage of precious memory of the heap. The Garbage Collector then has a tough time maintaining the memory for other resources.
On the other hand, the ArrayList is dynamic in nature. It provides for automatic resizing of the List. Moreover you need not specify the size at the beginning of the initialization part. The ArrayList is therefore much more widely used as compared to an Array in Java.

Monday, July 11, 2011

Java -- Inheritance.

I have a question on Inheritance in Java programming language. It is said that every class automatically extends the class Object. If it is so then how are we able to extend other classes?

Like:

class MyClass extends Test1 ---

but if it is extending Object class then it would be like this

class MyClass extends Object,Test1
--
--

which is not allowed in java.

Please comment on it.

ArrayList to File

This code deals with how to write data from an ArrayList to a file.ArrayList is populated from a table in datqabase.Then array list is iterated and the values are printed on text file.

CandidateClass
.java


package encapsulation;

import java.io.BufferedWriter;

import java.io.DataOutputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.io.FileWriter;

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.util.ArrayList;

import java.util.Iterator;

import encapsulation.BusinessClasses;

public class CandidateClass {

public static void main(String[] args)

{

BusinessClasses bc=new BusinessClasses();

ArrayList ae=((ArrayList)bc.candidateDetails());

File f1=new File("cand_list.txt");

try

{

f1.createNewFile();

FileWriter fstream = new FileWriter("cand_list.txt");

BufferedWriter out = new BufferedWriter(fstream);

PrintWriter pw =new PrintWriter(out);

Iterator it=ae.iterator();

int i=0;

while(it.hasNext())

{

String element = (String)it.next();

out.write(" ");

out.write(element);

i++;

if(i%2==0){

pw.println();

}

}

out.close();

}

catch (IOException e) {

System.out.println("Problem writing to file.");

System.err.println("IOException: " + e.getMessage());

}

}

}

//BusinessClasse.java

package encapsulation;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.ResultSetMetaData;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

public class BusinessClasses {

public static Connection getConnection() {

Connection conn=null;

try {

Class.forName("oracle.jdbc.driver.OracleDriver");

String url = "jdbc:oracle:thin:@10.2.0.114:1521:ORCL";

conn = DriverManager.getConnection(url,"AYUSHMAR1024062011","AYUSHMAR1024062011");

} catch (Exception e) {

e.printStackTrace();

}

return conn;

}

public List candidateDetails() {

Statement st=null;

Connection con=null;

ResultSet rs=null;

List ae=new ArrayList();

try{

con=getConnection();

st=con.createStatement();

String sql="select CANDIDATE_ID,CANDIDATE_NAME from AYUSH_CANDIDATE_MST";

rs=st.executeQuery(sql);

ResultSetMetaData metaData = rs.getMetaData();

int columnCount = metaData.getColumnCount();

while(rs.next()){

for(int i=1;i<=columnCount;i++)

{

ae.add(rs.getString(i));

}

}

}

catch(SQLException se)

{

se.printStackTrace();

}

return ae;

}

}