What is Java?
Java is a language developed by Sun Microsystems which allows World Wide Web pages to contain code that is executed on the browser. Because Java is based on a single "virtual machine" that all implementations of java emulate, it is possible for Java programs to run on any system which has a version of Java. It is also possible for the "virtual machine" emulator to make sure that Java programs downloaded through the web do not attempt to do unauthorized things.
What is an Object Oriented language?
A computer language can be aid to be Object Oriented if it provides support for the following:
Class:
A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind.
Object:
An instance of a class. A class must be instantiated into an object before it can be used in the software. More than one instance of the same class can be in existence at any one time.
Encapsulation:
The act of placing data and the operations that perform on that data in the same class. The class then becomes the 'capsule' or container for the data and operations.
Inheritence:
The reuse of base classes (superclasses) to form derived classes (subclasses). Methods and properties defined in the superclass are automatically shared by any subclass.
Polymorphism:
Same interface, different implementation. The ability to substitute one class for another. This means that different classes may contain the same method names, but the result which is returned by each method will be different as the code behind each method (the implementation) is different in each class.
What Is a Class?
In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model.
Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.
The following Bicycle class is one possible implementation of a bicycle:
Class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
void changeCadence(int newValue) {
cadence = newValue;
}
void changeGear(int newValue) {
gear = newValue;
}
void speedUp(int increment) {
speed = speed + increment;
}
void applyBrakes(int decrement) {
speed = speed - decrement;
}
void printStates() {
System.out.println("cadence:"+cadence+" speed:"+speed+" gear:"+gear);
}
}
The syntax of the Java programming language will look new to you, but the design of this class is based on the previous discussion of bicycle objects. The fields cadence, speed, and gear represent the object's state, and the methods (changeCadence, changeGear, speedUp etc.) define its interaction with the outside world.
You may have noticed that the Bicycle class does not contain a main method. That's because it's not a complete application; it's just the blueprint for bicycles that might be used in an application. The responsibility of creating and using new Bicycle objects belongs to some other class in your application.
Here's a BicycleDemo class that creates two separate Bicycle objects and invokes their methods:
class BicycleDemo {
public static void main(String[] args) {
// Create two different Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
// Invoke methods on those objects
bike1.changeCadence(50);
bike1.speedUp(10);
bike1.changeGear(2);
bike1.printStates();
bike2.changeCadence(50);
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.speedUp(10);
bike2.changeGear(3);
bike2.printStates();
}
}
The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles:
cadence:50 speed:10 gear:2
cadence:40 speed:20 gear:3
What Is an Object?
Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your bicycle.
Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.
Take a minute right now to observe the real-world objects that are in your immediate area. For each object that you see, ask yourself two questions: "What possible states can this object be in?" and "What possible behavior can this object perform?". Make sure to write down your observations. As you do, you'll notice that real-world objects vary in complexity; your desktop lamp may have only two possible states (on and off) and two possible behaviors (turn on, turn off), but your desktop radio might have additional states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in turn, will also contain other objects. These real-world observations all translate into the world of object-oriented programming.
A software object.
Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.
Consider a bicycle, for example:
A bicycle modeled as a software object.
By attributing state (current speed, current pedal cadence, and current gear) and providing methods for changing that state, the object remains in control of how the outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than 6.
Bundling code into individual software objects provides a number of benefits, including:
1. Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.
2. Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.
3. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.
4. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.
What is Encapsulation?
Encapsulation provides the basis for again modularity- by hiding information from unwanted outside access and attaching that information to only methods that need access to it. This binds data and operations tightly together and separates them from external access that may corrupt them intentionally or unintentionally.
Encapsulation is achieved by declaring variables as Private in a class- this gives access to data to only member functions of the class. A next level of accessibility is provided by the Protected keyword which gives the derived classes the access to the member variables of the base class- a variable declared as Protected can at most be accessed by the derived classes of the class.
What is Inheritance?
Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.
Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses: fig. A hierarchy of Bicycle classes
The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:
class MountainBike extends Bicycle {
// new fields and methods defining a mountain bike would go here
}
A hierarchy of bicycle classes.
This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.
What is Polymorphism?
Polymorphism gives us the ultimate flexibility in extensibility. Polymorphism is a term that describes a situation where one name may refer to different methods. In java there are two type of polymorphism: overloading type and overriding type.
When you override methods, java determines the proper methods to call at the program’s run time, not at the compile time. Overriding occurs when a class method has the same name and signature as a method in parent class. Overloading occurs when several methods have same names with different method signature. Overloading is determined at the compile time.
Example: Overloading
Class Book{
String title;
String publisher;
float price;
setBook(String title){}
setBook(String title, String publisher){}
setBook(String title, String publisher,float price){}
}
Example: Overriding
Class Tool{
void operate_it(){
}
}
Class ScrewDriver extends Tool{
void operate_it(){
}
}
What is an Interface?
A Tool class and its class hierarchy defines what a Tool can and cannot do in terms of its characteristics. However a Tool can have a different relationship with other parts of the world. For example, a Tool in a store could be managed by an inventory program. An inventory program doesn't care what class of items it manages as long as each item provides certain information, such as price and tracking number.
Instead of forcing class relationships on otherwise unrelated items, the inventory program sets up a protocol of communication. This protocol comes in the form of a set of constant and method definitions contained within an interface. The inventory interface would define, but not implement, methods that set and get the retail price, assign a tracking number, and so on.
To work in the inventory program, the Tool class must agree to this protocol by implementing the interface. When a class implements an interface, the class agrees to implement all the methods defined in the interface. Thus, the Tool class would provide the implementations for the methods that set and get retail price, assign a tracking number, and so on.
You use an interface to define a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. Interfaces are useful for the following:
• Capturing similarities among unrelated classes without artificially forcing a class relationship.
• Declaring methods that one or more classes are expected to implement.
• Revealing an object's programming interface without revealing its class.
An interface is a contract in the form of a collection of method and constant declarations. When a class implements an interface, it promises to implement all of the methods declared in that interface. Interfaces are useful for capturing similarities among unrelated classes without artificially forcing a class relationship, declaring methods that one or more classes are expected to implement and revealing an object's programming interface without revealing its class. Java uses ‘interface’ and ‘abstract Class’ to define interfaces.
What is Abstract classes & methods?
Abstract class is a class that has no direct instances, but whose descendants may have direct instances. There are case i which it is useful to define classes for which the programmer never intends to instantiate any objects; because such classes normally are used as bae-classes in inheritance hierarchies, we call such classes abstract classes These classes cannot be used to instantiate objects; because abstract classes are incomplete. Derived classes called concrete classesmust define the missing pieces.
Abstract classes normally contain one or more abstract methods or abstract properties, such methods or properties do not provide implementations, but our derived classes must override inherited abstract methods or properties to enable obejcts ot those derived classes to be instantiated, not to override those methods or properties in derived classes is syntax error, unless the derived class also is an abstract class.
In some cases, abstract classes constitute the top few levels of the hierarchy, for Example abstract class Shape with abstract method Draw() has tow derived abstract classe Shape2D & Shape3D inherites the method Draw() & also do not provide any implementation for it. Now we have normal classes Rectangle, Square & Circle inherites from Shape2D, and another group of classes Sphere, Cylinder & Cube inherites from Shape3D. All classes at the bottom of the hierarchy must override the abstract method Draw().
A class is made abstract by declaring it with Keyword abstract.
Example:
public abstract class Shape
{
//...Class implementation
public abstract void Draw(int x, int y)
{
//this method mustn't be implemented here.
//If we do implement it, the result is a Syntax Error.
}
}
public abstract class Shape2D : Shape
{
//...Class implementation
//...you do not have to implement the the method Draw(int x, int y)
}
public class Cricle : Shape2D
{
//here we should provide an implemetation for Draw(int x, int y)
public override void Draw(int x, int y)
{
//must do some work here
}
}
Difference between an abstract method & virtual method:
Virtual method has an implementation & provide the derived class with the option of overriding it. Abstract method does not provide an implementation & forces the derived class to override the method.
important Notes:
(a)Any Class with abstract method or property in it must be declared abstract
(b)Attempting to instantiate an object of an abstract class retults in a compilation error
Example:
Shape m_MyShape = new Shape(); //it is Wrong to that.
But we can do that.
Shape m_MyShape = new Circle(); // True
Or
Shape m_MyShape;
/*
declare refrences only, and the refrences can refer to intances of
any concrete classes derived from abstract class
*/
Circle m_MyCircle = new Circle();
m_MyShape = m_MyCircle; // Also True
Interface Vs Abstract Class?
There are three differences between an interface and an abstract class:
• you can implement multiple interfaces at the same time, but only extend one class,
• an abstract class is allowed to contain implementation (non-abstract methods, constructors, instance initializers and instance variables) and non-public members, and
• abstract classes may be a tiny bit faster (or they may not.)
Abstract class can contain abstract methods, abstract property as well as other members (just like normal class).
Interface can only contain abstract methods, properties but we don’t need to put abstract and public keyword. All the methods and properties defined in Interface are by default public and abstract.
Actually the first point is the reason for the existence of interfaces in Java: to provide a form of multiple inheritance. In languages with multiple implementation inheritance, an interface would be equivalent to a fully abstract class (a class with only public abstract members).
The above differentiation suggests when to use an abstract class and when to use an interface:
• use an abstract class, if you want to provide common implementation to subclasses,
• use an abstract class, if you want to declare non-public members,
• use an abstract class, if you want to be free to add new public methods in the future,
• use an interface if you're sure the API is stable for the long run
• use an interface if you want to provide the implementing classes the opportunity to inherit from other sources at the same time.
In general, prefer interfaces if you don't need to use an abstract class, because they provide more design flexibility.
//Abstarct Class
public abstract class Vehicles
{
private int noOfWheel;
private string color;
public abstract string Engine
{
get;
set;
}
public abstract void Accelerator();
}
//Interface
public interface Vehicles
{
string Engine
{
get;
set;
}
void Accelerator();
}
We can see abstract class contains private members also we can put some methods with implementation also. But in case of interface only methods and properties allowed.
We use abstract class and Interface for the base class in our application.
Friday, April 4, 2008
Wednesday, April 2, 2008
JSP Implicit Objects
JSP implicit objects
(a) request, (b) response, (c) out, (d) session,
(e) config, (f) application, (g) page, ( h)pageContext,
and (i) exception.
What are Implicit Objects?
When writing Servlets the available objects are fairly obvious as they are the parameters to methods, thus if you are overriding the doPost method you will have a signature of
public void doPost(HttpServletRequest request,
HttpServletResponse response)
When writing JSP pages the implicit objects are created automatically for you within the service method . You just have to know what the implicit objects are, but as most of them match closely to those available in Servlet methods they are not too difficult to memorise. You will have come across one of the implicit objects already with the out object which allows you to send information to the output stream.
Note that the implicit variables are only available within the jspService method and thus are not available within any declarations. Thus for example the following code will cause a compile time error.
<%!
public void amethod(){
out.print("Hello");
}
%>
1) The request and response implicit objects
The request implicit object is an instance of HttpServletRequest, and response is an instance of HttpServletResponse objects. They are available in a similar way to the request and response object passed to the doGet and doPost methods in servlets.
A typical use for the request is to get the details of HTTP query string such as query names and parameters.
<%= request.getQueryString() %>
Will display the query string after the name of the jsp file itself. Thus if this code is within a file called hello.jsp and is called with the url as follows
http://localhost:8080/chap03/hello.jsp?thisisthequerystring
The output will include thisisthequerystring as part of the page.
The response can be used for the same purposes as the HttpServletResponse in a servlet, such as adding cookies or headers.
The request and response objects are the same as the parameters to doPost and represent instances of HttpServletRequest and HttpServletResponse respectively.
3) The out implicit object
The out implicit object has a type of jsp.JspWriter. The out object can be used in a similar way to System.out is used in plain ordinary Java programs, i.e.
<%
out.print("Hello World");
%>
The parameters of out are sent to the output stream, which generally means they end up visible in the browser requesting the JSP page.
4)session
The session implicit object is an instance of
javax.servlet.http.HttpSession
The session concept is a way of allowing multiple requests from the same client to be group together as part of a single “conversation”. This is a way of getting around the basic architectural limitation within HTTP in that it was designed as a stateless protocol, i.e. web servers “forget” about each client as soon as a request has finished execution. The default way of logically linking multiple requests from the same client is by generating a cookie that stores a value unique to the client. After the first request establishes a session, each subsequent request reads that cookie and can thus identify the unique client.
With the session object you do not need the type of code required in a Servlet whereby you have to call the getSession method to access an existing session or start a new one. Typical uses of the session object are for getting and setting attributes. Thus you can add a new attribute to the session with code like the following.
<%
session.setAttribute("username","marcusgreen");
%>
5)config
The config implicit object is an instance of
javax.servlet.ServletConfig
And represents the parameters set up within the deployment descriptor. To set up the configuration a servlet is configured within web.xml , but instead of creating a element a element is created containing the name of the JSP page. Parameters are then created using the and tags.
The config object can be used to retrieve parameters using its
getInitParameter(String param)
method.
The config object can be used to retrieve the ServletContext object through its getServletContext method. Thus the following code retrieves information about the currently executing server, and in my own setup it generates the output.
Apache Tomcat/5.5.9
<%
ServletContext ct = config.getServletContext();
out.print(ct.getServerInfo());
%>
6) application
The application implicit object is an instance of javax.servlet.ServletContext. It refers to the overall web application environment that the JSP belongs to. According to the API docs
“Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.”
In Apache Tomcat a web application will be contained in an individual directory under the webapps directory. A typical use of the application object is to get access to the application wide initialisation parameters. Because the application and config objects have similar and slightly confusing uses the following code shows how they can be used along with a deployment descriptor (WEB.XML) that sets up the appropriate initialisation parameters for them.
The file index.jsp
<%
/*for parameters declared at the application level .
*i.e. under the WEB-APP tag of the deployment descriptor
*/
out.print(application.getInitParameter("myparam"));
/*for a specific resource within an application
*identified as a servlet in the deployment descriptor
*/
out.print(config.getInitParameter("myparam2"));
%>
7) The page implicit object
The page implicit object is of type Object and it is assigned a reference to the servlet that executing the _jspService() method. Thus in the Servlet generated by tomcat the page object is created as
Object page = this;
Because page is of type Object it is of less direct use than simply accessing the implicit this object. To access any of the methods of the servlet through page it must be first cast to type Servlet. Thus the two following lines of code are equivalent.
<% this.log("log message"); %>
<% ((HttpServlet)page).log("anothermessage"); %>
As you probably will not be using the page object in your own code the main thing to remember for the exam is that it is not the same as the pageContext object and that it is of type Object.
8) The pageContext implicit object
The pageContext object has a type of javax.servlet.jsp.PageContext and according to the API documents
“A PageContext instance provides access to all the namespaces associated with a JSP page, provides access to several page attributes, as well as a layer above the implementation details. Implicit objects are added to the pageContext automatically “http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/PageContext.html
So it can be seen as a convenience object for tasks such as transferring requests to other web resources. Much of its functionality appears to be for the convenience of generating the servlet from the JSP, thus the following example of a servlet generated from the Tomcat container shows how PageContext is used to populate other implicit objects.
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
A typical use of the pageContext is to to include another resource or forward to another resource. Thus the following would forward from the current page to menu.jsp
<%
pageContext.forward("menu.jsp");
%>
9) The exception implicit object
The exception implicit object is of type
java.lang.Throwable
This object is only available to pages that have isErrorPage set to true with the directive
<%@ page isErrorPage='true' %>
The exception object refers to the exception triggered by the page that uses this page as an exception handler
The following code demonstrates the use of the exception implicit object. The first page uses the errorPage directive to set up the JSP page to use when an error occurs, and the second page called ErrorPage.jsp uses the isErrorPage directive to set itself up to catch the error.
First page
<%@page errorPage="ErrorPage.jsp" %>
<%
int i=10;
/*Divide by zero, generates an error */
out.print(i/0);
%>
ErrorPage.jsp
<%@ page isErrorPage='true' %>
<%
out.print("
out.print(exception.getMessage());
%>
Declarative handling of exceptions
It is also possible to map HTTP error codes and or Java exception types to an error page in the deployment descriptor. This is done at the web application level by using the tag which is a child of the tag. Thus the following tags would re-direct all SQL exception errors to the /errorpage.jsp page.
java.sql.SQLException
/errorpage.jsp
The following tags would re-direct all HTTP 404 errors to the /errorpage.jsp page
404
/errorPage.jsp
(a) request, (b) response, (c) out, (d) session,
(e) config, (f) application, (g) page, ( h)pageContext,
and (i) exception.
What are Implicit Objects?
When writing Servlets the available objects are fairly obvious as they are the parameters to methods, thus if you are overriding the doPost method you will have a signature of
public void doPost(HttpServletRequest request,
HttpServletResponse response)
When writing JSP pages the implicit objects are created automatically for you within the service method . You just have to know what the implicit objects are, but as most of them match closely to those available in Servlet methods they are not too difficult to memorise. You will have come across one of the implicit objects already with the out object which allows you to send information to the output stream.
Note that the implicit variables are only available within the jspService method and thus are not available within any declarations. Thus for example the following code will cause a compile time error.
<%!
public void amethod(){
out.print("Hello");
}
%>
1) The request and response implicit objects
The request implicit object is an instance of HttpServletRequest, and response is an instance of HttpServletResponse objects. They are available in a similar way to the request and response object passed to the doGet and doPost methods in servlets.
A typical use for the request is to get the details of HTTP query string such as query names and parameters.
<%= request.getQueryString() %>
Will display the query string after the name of the jsp file itself. Thus if this code is within a file called hello.jsp and is called with the url as follows
http://localhost:8080/chap03/hello.jsp?thisisthequerystring
The output will include thisisthequerystring as part of the page.
The response can be used for the same purposes as the HttpServletResponse in a servlet, such as adding cookies or headers.
The request and response objects are the same as the parameters to doPost and represent instances of HttpServletRequest and HttpServletResponse respectively.
3) The out implicit object
The out implicit object has a type of jsp.JspWriter. The out object can be used in a similar way to System.out is used in plain ordinary Java programs, i.e.
<%
out.print("Hello World");
%>
The parameters of out are sent to the output stream, which generally means they end up visible in the browser requesting the JSP page.
4)session
The session implicit object is an instance of
javax.servlet.http.HttpSession
The session concept is a way of allowing multiple requests from the same client to be group together as part of a single “conversation”. This is a way of getting around the basic architectural limitation within HTTP in that it was designed as a stateless protocol, i.e. web servers “forget” about each client as soon as a request has finished execution. The default way of logically linking multiple requests from the same client is by generating a cookie that stores a value unique to the client. After the first request establishes a session, each subsequent request reads that cookie and can thus identify the unique client.
With the session object you do not need the type of code required in a Servlet whereby you have to call the getSession method to access an existing session or start a new one. Typical uses of the session object are for getting and setting attributes. Thus you can add a new attribute to the session with code like the following.
<%
session.setAttribute("username","marcusgreen");
%>
5)config
The config implicit object is an instance of
javax.servlet.ServletConfig
And represents the parameters set up within the deployment descriptor. To set up the configuration a servlet is configured within web.xml , but instead of creating a
The config object can be used to retrieve parameters using its
getInitParameter(String param)
method.
The config object can be used to retrieve the ServletContext object through its getServletContext method. Thus the following code retrieves information about the currently executing server, and in my own setup it generates the output.
Apache Tomcat/5.5.9
<%
ServletContext ct = config.getServletContext();
out.print(ct.getServerInfo());
%>
6) application
The application implicit object is an instance of javax.servlet.ServletContext. It refers to the overall web application environment that the JSP belongs to. According to the API docs
“Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.”
In Apache Tomcat a web application will be contained in an individual directory under the webapps directory. A typical use of the application object is to get access to the application wide initialisation parameters. Because the application and config objects have similar and slightly confusing uses the following code shows how they can be used along with a deployment descriptor (WEB.XML) that sets up the appropriate initialisation parameters for them.
The file index.jsp
<%
/*for parameters declared at the application level .
*i.e. under the WEB-APP tag of the deployment descriptor
*/
out.print(application.getInitParameter("myparam"));
/*for a specific resource within an application
*identified as a servlet in the deployment descriptor
*/
out.print(config.getInitParameter("myparam2"));
%>
7) The page implicit object
The page implicit object is of type Object and it is assigned a reference to the servlet that executing the _jspService() method. Thus in the Servlet generated by tomcat the page object is created as
Object page = this;
Because page is of type Object it is of less direct use than simply accessing the implicit this object. To access any of the methods of the servlet through page it must be first cast to type Servlet. Thus the two following lines of code are equivalent.
<% this.log("log message"); %>
<% ((HttpServlet)page).log("anothermessage"); %>
As you probably will not be using the page object in your own code the main thing to remember for the exam is that it is not the same as the pageContext object and that it is of type Object.
8) The pageContext implicit object
The pageContext object has a type of javax.servlet.jsp.PageContext and according to the API documents
“A PageContext instance provides access to all the namespaces associated with a JSP page, provides access to several page attributes, as well as a layer above the implementation details. Implicit objects are added to the pageContext automatically “http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/PageContext.html
So it can be seen as a convenience object for tasks such as transferring requests to other web resources. Much of its functionality appears to be for the convenience of generating the servlet from the JSP, thus the following example of a servlet generated from the Tomcat container shows how PageContext is used to populate other implicit objects.
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
A typical use of the pageContext is to to include another resource or forward to another resource. Thus the following would forward from the current page to menu.jsp
<%
pageContext.forward("menu.jsp");
%>
9) The exception implicit object
The exception implicit object is of type
java.lang.Throwable
This object is only available to pages that have isErrorPage set to true with the directive
<%@ page isErrorPage='true' %>
The exception object refers to the exception triggered by the page that uses this page as an exception handler
The following code demonstrates the use of the exception implicit object. The first page uses the errorPage directive to set up the JSP page to use when an error occurs, and the second page called ErrorPage.jsp uses the isErrorPage directive to set itself up to catch the error.
First page
<%@page errorPage="ErrorPage.jsp" %>
<%
int i=10;
/*Divide by zero, generates an error */
out.print(i/0);
%>
ErrorPage.jsp
<%@ page isErrorPage='true' %>
<%
out.print("
Here is the error message
");out.print(exception.getMessage());
%>
Declarative handling of exceptions
It is also possible to map HTTP error codes and or Java exception types to an error page in the deployment descriptor. This is done at the web application level by using the
java.sql.SQLException
/errorpage.jsp
The following tags would re-direct all HTTP 404 errors to the /errorpage.jsp page
Subscribe to:
Posts (Atom)