Saturday, March 23, 2013

JSP - Auto Page Refresh


Consider a webpage which is displaying live game score or stock market status or currency exchange ration. For all such type of pages, you would need to refresh your web page regularly using referesh or reload button with your browser.
JSP makes this job easy by providing you a mechanism where you can make a webpage in such a way that it would refresh automatically after a given interval.
The simplest way of refreshing a web page is using method setIntHeader() of response object. Following is the signature of this method:
public void setIntHeader(String header, int headerValue)
This method sends back header "Refresh" to the browser along with an integer value which indicates time interval in seconds.

Auto Page Refresh Example:

Following example would use setIntHeader() method to set Refresh header to simulate a digital clock:
<%@ page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Auto Refresh Header Example</title>
</head>
<body>
<center>
<h2>Auto Refresh Header Example</h2>
<%
   // Set refresh, autoload time as 5 seconds
   response.setIntHeader("Refresh", 5);
   // Get current time
   Calendar calendar = new GregorianCalendar();
   String am_pm;
   int hour = calendar.get(Calendar.HOUR);
   int minute = calendar.get(Calendar.MINUTE);
   int second = calendar.get(Calendar.SECOND);
   if(calendar.get(Calendar.AM_PM) == 0)
      am_pm = "AM";
   else
      am_pm = "PM";
   String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
   out.println("Crrent Time: " + CT + "\n");
%>
</center>
</body>
</html>

Monday, March 18, 2013

JSP - Implicit Objects


SP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.
JSP supports nine Implicit Objects which are listed below:
ObjectDescription
requestThis is the HttpServletRequest object associated with the request.
responseThis is the HttpServletResponse object associated with the response to the client.
outThis is the PrintWriter object used to send output to the client.
sessionThis is the HttpSession object associated with the request.
applicationThis is the ServletContext object associated with application context.
configThis is the ServletConfig object associated with the page.
pageContextThis encapsulates use of server-specific features like higher performance JspWriters.
pageThis is simply a synonym for this, and is used to call the methods defined by the translated servlet class.
ExceptionThe Exception object allows the exception data to be accessed by designated JSP.
The request Object:
The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client requests a page the JSP engine creates a new object to represent that request.
The request object provides methods to get HTTP header information including form data, cookies, HTTP methods etc.

The response Object:

The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the server creates the request object, it also creates an object to represent the response to the client.
The response object also defines the interfaces that deal with creating new HTTP headers. Through this object the JSP programmer can add new cookies or date stamps, HTTP status codes etc.

The out Object:

The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send content in a response.
The initial JspWriter object is instantiated differently depending on whether the page is buffered or not. Buffering can be easily turned off by using the buffered='false' attribute of the page directive.
The JspWriter object contains most of the same methods as the java.io.PrintWriter class. However, JspWriter has some additional methods designed to deal with buffering. Unlike the PrintWriter object, JspWriter throws IOExceptions.
Following are the important methods which we would use to write boolean char, int, double, object, String etc.
MethodDescription
out.print(dataType dt)Print a data type value
out.println(dataType dt)Print a data type value then terminate the line with new line character.
out.flush()Flush the stream.
The session Object:
The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same way that session objects behave under Java Servlets.
The session object is used to track client session between client requests.
The application Object:
The application object is direct wrapper around the ServletContext object for the generated Servlet and in reality an instance of a javax.servlet.ServletContext object.
This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method.
By adding an attribute to application, you can ensure that all JSP files that make up your web application have access to it.

The config Object:

The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around the ServletConfig object for the generated servlet.
This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters such as the paths or file locations etc.
The following config method is the only one you might ever use, and its usage is trivial:
 
config.getServletName();
This returns the servlet name, which is the string contained in the <servlet-name> element defined in the WEB-INF\web.xml file
The pageContext Object:
The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is used to represent the entire JSP page.
This object is intended as a means to access information about the page while avoiding most of the implementation details.
This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object.
The pageContext object also contains information about the directives issued to the JSP page, including the buffering information, the errorPageURL, and page scope.
The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four scopes. It also supports more than 40 methods, about half of which are inherited from the javax.servlet.jsp. JspContext class.
One of the important methods is removeAttribute, which accepts either one or two arguments. For example, pageContext.removeAttribute ("attrName") removes the attribute from all scopes, while the following code only removes it from the page scope:
 
pageContext.removeAttribute("attrName", PAGE_SCOPE);

The page Object:

This object is an actual reference to the instance of the page. It can be thought of as an object that represents the entire JSP page.
The page object is really a direct synonym for the this object.
The exception Object:
The exception object is a wrapper containing the exception thrown from the previous page. It is typically used to generate an appropriate response to the error condition.

Saturday, March 16, 2013

JSP Life Cycle


A JSP life cycle can be defined as the entire process from its creation till the destruction which is similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet.
The following are the paths followed by a JSP
  • Compilation
  • Initialization
  • Execution
  • Cleanup
The four major phases of JSP life cycle are very similar to Servlet Life Cycle and they are as follows:
JSP Life Cycle

JSP Compilation:

When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.
The compilation process involves three steps:
  • Parsing the JSP.
  • Turning the JSP into a servlet.
  • Compiling the servlet.

JSP Initialization:

When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to perform JSP-specific initialization, override the jspInit() method:
public void jspInit(){
  // Initialization code...
}
Typically initialization is performed only once and as with the servlet init method, you generally initialize database connections, open files, and create lookup tables in the jspInit method.

JSP Execution:

This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP.
The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as follows:
void _jspService(HttpServletRequest request, 
                 HttpServletResponse response)
{
   // Service handling code...
}
The _jspService() method of a JSP is invoked once per a request and is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods ie. GET, POST, DELETE etc.

JSP Cleanup:

The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.
The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when you need to perform any cleanup, such as releasing database connections or closing open files.
The jspDestroy() method has the following form:
public void jspDestroy()
{
   // Your cleanup code goes here.
}

JSP Architecture


The web server needs a JSP engine ie. container to process JSP pages. The JSP container is responsible for intercepting requests for JSP pages. This tutorial makes use of Apache which has built-in JSP container to support JSP pages development.
A JSP container works with the Web server to provide the runtime environment and other services a JSP needs. It knows how to understand the special elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web Application.
JSP Architecture

JSP Processing:

The following steps explain how the web server creates the web page using JSP:
  • As with a normal page, your browser sends an HTTP request to the web server.
  • The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead of .html.
  • The JSP engine loads the JSP page from disk and converts it into a servlet content. This conversion is very simple in which all template text is converted to println( ) statements and all JSP elements are converted to Java code that implements the corresponding dynamic behavior of the page.
  • The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine.
  • A part of the web server called the servlet engine loads the Servlet class and executes it. During execution, the servlet produces an output in HTML format, which the servlet engine passes to the web server inside an HTTP response.
  • The web server forwards the HTTP response to your browser in terms of static HTML content.
  • Finally web browser handles the dynamically generated HTML page inside the HTTP response exactly as if it were a static page.
All the above mentioned steps can be shown below in the following diagram:
JSP Processing
Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and whether the modification date on the JSP is older than the servlet. If the JSP is older than its generated servlet, the JSP container assumes that the JSP hasn't changed and that the generated servlet still matches the JSP's contents. This makes the process more efficient than with other scripting languages (such as PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a servlet without having to be a Java programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular servlet

Friday, March 15, 2013

Servlet Life Cycle


A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet
  • The servlet is initialized by calling the init () method.
  • The servlet calls service() method to process a client's request.
  • The servlet is terminated by calling the destroy() method.
  • Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in details.

The init() method :

The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.
The init method definition looks like this:
public void init() throws ServletException {
  // Initialization code...
}

The service() method :

The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method:
public void service(ServletRequest request, 
                    ServletResponse response) 
      throws ServletException, IOException{
}
The service () method is called by the container and service method invokes doGe, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request. Here are the signature of these two methods.

The doGet() Method

A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request,
                  HttpServletResponse response)
    throws ServletException, IOException {
    // Servlet code
}

The doPost() Method

A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method.
public void doPost(HttpServletRequest request,
                   HttpServletResponse response)
    throws ServletException, IOException {
    // Servlet code
}

The destroy() method :

The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this:
  public void destroy() {
    // Finalization code...
  }

Architecture Digram:

The following figure depicts a typical servlet life-cycle scenario.
  • First the HTTP requests coming to the server are delegated to the servlet container.
  • The servlet container loads the servlet before invoking the service() method.
  • Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet.
Servlet Life Cycle

Thursday, March 14, 2013

Shallow Cloning and Deep Cloning in Java

Cloning is of 2 Types:

1. Shallow Cloning  2. Deep Cloning

Whenever clone() method is used 2 different objects are created in 2 different memory locations. So
separate memory is occupied.

If a class contains  X, Y variable and clone is applied two different objects are created in two different situations.

In Shallow Cloning  main problem is instance variables are common for both objects , so if one object is modifed then automatically second object is also modified.

In deep cloning 2 different objects are created in 2 different memory locations , if in case original object is modified then also its duplicate object won't effect , why because there is  no relation between original and duplicate object.



KNOWLEDGE HUB: How many ways can you create an object in Java

KNOWLEDGE HUB: How many ways can you create an object in Java

Wednesday, March 13, 2013

different ways to create an object in Java

There are 4 ways of creating objects in Java.

1. Using new operator

Employee emp = new Employee();

Here , we are creating Employee class object  'emp' using new operator.

2. Using factrory methods:

NumberFormat nf  = NumberFormat.getNumberInstace();

Here, we are creatig NumberFormat object using the factory method getNumberInstacne().

3. Using newInstance() method .

(a) First,store the class name  'Employee' as string into an  object. For this purpose , factory method
forName() of the class 'Class' will be useful.

Class c = Class.forName("Employee");

Note: class with the name 'Class' in java.lang package.
(b) create another object to the class whose name is in the object c . For this purpose , we need
newInstance()  method of the class 'Class' . as:

Employee obj = (Employee)c.newInstance();

4. By cloning an already available object, we can create another object . Creating exact copy of an
existing object is called 'cloning':

Employee obj1 = new Employee();
Employee obj2 = (Employee)obj1.clone();

Constructor VS Method in Java

Constructor
 Method
A constructor is used to initialize the instance variables of a class.
A Method is used for any general purpose processing or calculations.
A constructors name and class name should be same.
A method’s name and class name can be same or different.
A constructor is called at the time of creating the object.
A method can be called after creating the object.
A Constructor  is called only once per object.
A method can be called several times on the object.
A constructor is called and executed automatically.
A method is executed only when we call it.


Tuesday, March 12, 2013

Difference between Set and List in Java

Set:

1. A set represents a collection of elements . Order of the elements may change in the set.
2. Set will not allow duplicate values to be stored.
3. Accessing elements by their index(position number) is not possible in case of sets.
4.Sets will not allow null elements.

List:

1. A List represents ordered collection of elements . List preserves the order of elements in
which they are entered.
2. List will allow duplicate value.
3.Accessing elements by index is possible in lists.
4. Lists allow null elements to be stored.

Sunday, March 10, 2013

Difference between HashMap and Hashtable in Java

HashMap:

1. HashMap object is not synchronized by default.
2. In case of a single thread , using HashMap is faster than the Hashtable.
3. HashMap allows null keys and null values to be stored.
4. Iterator in the HashMap is fail-fast . This means iterator will produce exception if concurrent
updates are made to the HashMap.
5. We can make HashMap object synchronied using synchronizedMap() method as:

Collections.synchronizedMap(new HashMap())

Hashtable:

1. Hashtable object is synchronized by default.
2.In case fo multiple threads , using Hashtable is advisable. With a single thread, Hashtable
becomes slow.
3.Hashtable does not allow null keys or values.
4.Enumeration for the Hashtable is not fail-fast. This means even if concurrent updations
are done to to Hashtable, there will not be any incorrect results produced by the Enumeration.


Saturday, March 9, 2013

Difference between ArrayList and Vector in Java

ArrayList:
---------------
1.Array List object is not synchronized by default.
2.In case of a single thread ,using ArrayList is faster than the vector.
3.ArrayList increases its size every time by 50 percent(half).

4. We can synchronize Arraylist using synchronizedList() mehtod as:

List  l = Collections.SynchronizedList(new ArrayList());

Vector:
--------
1.Vector object is synchronized by default.
2. In case of multiple threads, using Vector is advisable. With a single  thread,
   Vector becomes slow.
3. Vector increases its size every time by doubling it.

Friday, March 8, 2013

difference between sleep() and wait() in Java

Both the sleep() and wait() methods are used to suspend a thread execution for a specified time.
When sleep() is executed inside a synchronized block, the object is still under lock .

When wait() method is executed,it breaks the synchronized block , so that the object lock is removed
and it is available.

Generally , sleep() is used for making a thread to wait for some time.But wait() is used in connection
with notify()  or notifyAll() methods in thread communication.

sleep method present in Thread class, wait method present in Object class.
sleep method is static , wait is non static method

Wednesday, March 6, 2013

About Sachin Ramesh Tendulkar



"Sachin Ramesh Tendulkar"                  
                              God of Cricket

   "Commit all your crimes when Sachin is playing... bcoz even GOD is busy watching at his PLAY! "


Perhaps the most complete batsman and the most worshipped cricketer in the world, Tendulkar holds just about every batting record worth owning in the game Following Sachin Tendulkar records list has been growing every year, and will grow until he plays.
            There are no apparent weaknesses in Tendulkar's game. He can score all around the wicket, off both front foot and back, can tune his technique to suit every condition, temper his game to suit every situation, and has made runs in all parts of the world in all conditions




                                                                                                                *As of on Jan'11


List of 100 Records


1.Highest individual score by a single player – 200*
2.First player to play a record 400 innings
3.Number of consecutive ODI appearances – 190 matches
4.Cricket grounds played on – 90 grounds
5.Record number of matches played – 442 matches6.Most runs in a cricket career – 17,598 runs
7.Record number of ODI centuries – 46 Centuries
8.Record number of centuries in ODIs against an opponent – 9 Centuries
9.Record number of centuries in tournament finals – 6 Centuries
10.Record number of centuries in all formats against an opponent – 19 centuries

11.Record number of Test Centuries - 51 Centuries (More than Half Century Centuries in Test Cricket)
12.First player to score 10,000 runs
13.First player to score 11,000 runs
14.First player to score 12,000 runs
15.First player to score 13,000 runs
16.First player to score 14,000 runs
17.First player to score 15,000 runs
18.First player to score 16,000 runs
19.First player to score 17,000 runs
20.Only male player to score a double century in ODIs
21.Tendulkar has scored more than 1,000 runs against every major cricket playing nation
22.Sachin is the only player to score more than 3000 runs against a single opponent – Sri Lanka and Australia
23.Holds the record to score more than 1,000 runs in a single calender year. He has done this 7 times so far.
24.Most number of runs in tournament finals – 1833 runs
25.Most fours in an innings – 25 against South Africa
26.Record number of scores above 150 in an innings – 5
27.Most Half Centuries in ODIs – 93 Half Centuries
28.Highest number of scores over 50 – 139
29.Most Man of the Match awards in ODIs – 61
30.Most Man of the Series awards in ODIs – 19

31.Most half centuries in world cup matches – 13
32.Sachin Tendulkar holds the record for the most runs in ODIs in a calendar year – 1894 runs in 1998
33.Second Fastest to reach 8000 test runs. Record recently broken by Kumar Sangakarra
34.Fastest to reach 12,000 test runs
35.Fastest to reach 13,000 test runs
36.Record centuries in a calendar year – 9 centuries in 1998
37.Highest partnership for any ODI wicket – 331 runs with Rahul Dravid
38.Highest partnership for 2nd wicket in ODIs – 331 runs with Rahul Dravid
39.Highest partnership for 3rd wicket in ODIs – 237* runs with Rahul Dravid

40.Highest partnership aggregated by a pair – 8227 runs with Sourav Ganguly
41.Record opening partnership pair – 6609 runs with Sourav Ganguly
42.Most century partnerships – 26 partnerships with Sourav Ganguly
43.4 wickets and Century in the same match – Against Australia in 1998
44.Sachin Tendulkar has been dismissed a record 3 times on 99 in ODIs
45.Sachin has been the most dismissed batsman in the 90s in International cricket – 24
46.Most 200 run partnerships in ODIs – 6
47.Most century partnerships by an opening pair – 21 with Sourav Ganguly
48.Record number of runs in a cricket world cup – 673 runs in 2003

49.Most runs in cricket world cups combined – 1796 runs
50.Most centuries in International cricket – 94 centuries
51.On Sachin’s Debut, he was the second youngest debutant after Aaqib Javed of Pakistan52.First batsman to complete 31,000 International runs
53.Most test runs – 13447 runs
54.Most dismissals in the 90s in ODIs – 17
55.Most number of Test appearances - 169
56.Most fours in test cricket – 1734+
57.Most century partnerships in Tests – 17 with Rahul Dravid
58.Highest score by an Indian captain – 217 against New Zealand
59.More than 1000 test runs in a single calendar year – 5 times

60.Record number of man of the match awards by an Indian in Test matches – 14 times
61.First batsman to score 50 international centuries
62.First batsman to score 60 International centuries
63.Tendulkar holds the record for being the only batsman to score 70 International centuries
64.Tendulkar holds the record for being the only batsman to score 80 International centuries
65.Tendulkar holds the record for being the only batsman to score 90 International centuries
66.Sachin Tendulkar is the only player to have scored century on debut in the Irani trophy, Ranji trophy and Duleep trophy
67.Most Centuriess in World cup Cricket – 4
68.Most Half Centuries in World Cup cricket – 17
69.Most boundaries in International cricket – 3675

70.Most half centuries in International cricket – 149
71.Most runs in a single edition of the IPL – 618 runs
72.Most runs scored in test matches away from home – 7819 runs
73.Highest overall partnership runs, in all formats combined – 12,400 runs with Sourav Ganguly
74.Most matches in a career – 606 matches
75.Sachin Tendulkar has played for a record number of consecutive matches for India – 239 matches
76.Highest partnership for the 3rd wicket in World Cup – 237 runs with Rahul Dravid
77.Fastest to reach 10,000 Test runs
78.Sachin is currently second after Sanath Jayasuriya for the most ODI appearances, soon expected to overtake
79.Sachin Tendulkar scored 5 centuries before he turned 20
80.Most fours in ODI cricket – 1927 boundaries


81.Ranked by Wisden as the Best ODI batsman of all time
82.Ranked by Wisden as the Second Best Test batsman of all time
83.Highest Indian last wicket partnership – 133 runs with Zaheer Khan
84.Most number of Man of the Match awards in World Cup
85.Sachin Tendulkar and Vinod Kambli were involved in a 664 run partnership in Harris Shield game in 1988. A record broken this year
86.In 1992, Sachin became the first overseas player to play for Yorkshire at the age of 19
87.Has the least percentage of Man of the Match awards when on the losing side. Out of the 56 times, India has lost 5 times
88.Sachin has won the Padma Shri, Arjuna Award and Rajiv Gandhi Khel Ratna awards, and he is the only cricketer to receive them all
89.One of the few batsmen to have Centuries against all Test Playing countries
90.The first batsman to be given out by a Third Umpire TV reviewal system
91.Sachin holds the record for being the only player to have 40 wickets and 11000 runs in Test cricket
92.Sachin holds the record for being the only player to have 150 wickets and 15000 runs in ODI cricket

93.Sachin Tendulkar holds the best average amongst the batsman who have crossed 10,000 ODI runs
94.The highest run scorer in the 199 and 2003 cricket world cups
95.Sachin is the only player to have more than 100, fifty plus scores
96.The only batsman to have scored more than 2 centuries against all Test playing nations
97.Sachin has completed his Century by hitting a 6, on four different occasions in test matches, a record shared by Ken Barrington
98.Only cricketer to have done 10,000 runs, 100 wickets and 100 catches in ODIs
99.The only player to be in Top 100 of ICC rankings for 10 years
100.Sachin is the cricketer to have a record number of records.

Take a Bow Master!!!