Java Server Pages
03:18What is java
Java is a programming language originally developed by James Gosling at Sun Microsystems (which has since merged into Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++, but it has fewer low-level facilities than either of them. Java applications are typically compiled to bytecode (class file) that can run on any Java virtual machine (JVM) regardless of computer architecture. Java is a general-purpose, concurrent, class-based, object-oriented language that is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" (WORA), meaning that code that runs on one platform does not need to be recompiled to run on another. Java is as of 2012 one of the most popular programming languages in use, particularly for client-server web applications, with a reported 10 million users.[10][11]
The original and reference implementation Java compilers, virtual machines, and class libraries were developed by Sun from 1991 and first released in 1995. As of May 2007, in compliance with the specifications of the Java Community Process, Sun relicensed most of its Java technologies under the GNU General Public License. Others have also developed alternative implementations of these Sun technologies, such as the GNU Compiler for Java and GNU Classpath.
why we use java
Java is a programming language and computing platform first released by Sun Microsystems in 1995. It is the underlying technology that powers state-of-the-art programs including utilities, games, and business applications. Java runs on more than 850 million personal computers worldwide, and on billions of devices worldwide, including mobile and TV devices.
Why do I need Java?
There are lots of applications and websites that won't work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere!
Why do I need Java?
There are lots of applications and websites that won't work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere!
Usage
Java technology is a high-level programming and a platform independent language. Java is designed to work in the distributed environment on the Internet. Java has a GUI features that provides you better "look and feel" over the C++ language, moreover it is easier to use than C++ and works on the concept of object-oriented programming model. Java enable us to play online games, video, audio, chat with people around the world, Banking Application, view 3D image and Shopping Cart. Java find its extensive use in the intranet applications and other e-business solutions that are the grassroots of corporate computing. Java , regarded as the most well described and planned language to develop an applications for the Web.
Java is a well known technology which allows you for software designed and written only once for an "virtual machine" to run on a different computers, supports various Operating System like Windows PCs, Macintoshes, and Unix computers. On the web aspect, Java is popular on web servers, used by many of the largest interactive websites. Java is used to create standalone applications which may run on a single computer or in distributed network. It is also be used to create a small application program based on applet, which is further used for Web page. Applets make easy and possible to interact with the Web page.
Introduction to JSP
JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pages based on HTML, XML, or other document types. Released in 1999 by Sun Microsystems[1], JSP is similar to PHP, but it uses the Java programming language.
To deploy and run JavaServer Pages, a compatible web server with a servlet container, such as Apache Tomcat or Jetty, is required.
Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server side scripting support for creating database driven web applications. JSP enable the developers to directly insert java code into jsp file, this makes the development process very simple and its maintenance also becomes very easy. JSP pages are efficient, it loads into the web servers memory on receiving the request very first time and the subsequent calls are served within a very short period of time.
In today's environment most web sites servers dynamic pages based on user request. Database is very convenient way to store the data of users and other things. JDBC provide excellent database connectivity in heterogeneous database environment. Using JSP and JDBC its very easy to develop database driven web application.
Take the HTML file you used in the previous exercise. Change its extension from ".html" to ".jsp". Now load the new file, with the ".jsp" extension, in your browser.
You will see the same output, but it will take longer! But only the first time. If you reload it again, it will load normally.
What is happening behind the scenes is that your JSP is being turned into a Java file, compiled and loaded. This compilation only happens once, so after the first load, the file doesn't take long to load anymore. (But everytime you change the JSP file, it will be re-compiled again.)
Of course, it is not very useful to just write HTML pages with a .jsp extension! We now proceed to see what makes JSP so useful.
To deploy and run JavaServer Pages, a compatible web server with a servlet container, such as Apache Tomcat or Jetty, is required.
Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server side scripting support for creating database driven web applications. JSP enable the developers to directly insert java code into jsp file, this makes the development process very simple and its maintenance also becomes very easy. JSP pages are efficient, it loads into the web servers memory on receiving the request very first time and the subsequent calls are served within a very short period of time.
In today's environment most web sites servers dynamic pages based on user request. Database is very convenient way to store the data of users and other things. JDBC provide excellent database connectivity in heterogeneous database environment. Using JSP and JDBC its very easy to develop database driven web application.
Your first JSP
JSP simply puts Java inside HTML pages. You can take any existing HTML page and change its extension to ".jsp" instead of ".html". In fact, this is the perfect exercise for your first JSP.Take the HTML file you used in the previous exercise. Change its extension from ".html" to ".jsp". Now load the new file, with the ".jsp" extension, in your browser.
You will see the same output, but it will take longer! But only the first time. If you reload it again, it will load normally.
What is happening behind the scenes is that your JSP is being turned into a Java file, compiled and loaded. This compilation only happens once, so after the first load, the file doesn't take long to load anymore. (But everytime you change the JSP file, it will be re-compiled again.)
Of course, it is not very useful to just write HTML pages with a .jsp extension! We now proceed to see what makes JSP so useful.
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.
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
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 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.

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
JSP life cycle
The key to understanding the low-level functionality of JSP is to understand the simple life cycle they follow.
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
The compilation process involves three steps:
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.
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:
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.
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:
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

(1) 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.
(2) 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... } |
(3) 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... } |
(4) 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-Scriptlets
Scriptlets
We have already seen how to embed Java expressions in JSP pages by putting them between the <%= and %> character sequences.But it is difficult to do much programming just by putting Java expressions inside HTML.
JSP also allows you to write blocks of Java code inside the JSP. You do this by placing your Java code between <% and %> characters (just like expressions, but without the = sign at the start of the sequence.)
This block of code is known as a "scriptlet". By itself, a scriptlet doesn't contribute any HTML (though it can, as we will see down below.) A scriptlet contains Java code that is executed every time the JSP is invoked.
Here is a modified version of our JSP from previous section, adding in a scriptlet.
<HTML> <BODY> <% // This is a scriptlet. Notice that the "date" // variable we declare here is available in the // embedded expression later on. System.out.println( "Evaluating date now" ); java.util.Date date = new java.util.Date(); %> Hello! The time is now <%= date %> </BODY> </HTML>If you run the above example, you will notice the output from the "System.out.println" on the server log. This is a convenient way to do simple debugging (some servers also have techniques of debugging the JSP in the IDE. See your server's documentation to see if it offers such a technique.) By itself a scriptlet does not generate HTML. If a scriptlet wants to generate HTML, it can use a variable called "out". This variable does not need to be declared. It is already predefined for scriptlets, along with some other variables. The following example shows how the scriptlet can generate HTML output.
<HTML> <BODY> <% // This scriptlet declares and initializes "date" System.out.println( "Evaluating date now" ); java.util.Date date = new java.util.Date(); %> Hello! The time is now <% // This scriptlet generates HTML output out.println( String.valueOf( date )); %> </BODY> </HTML>Here, instead of using an expression, we are generating the HTML directly by printing to the "out" variable. The "out" variable is of type javax.servlet.jsp.JspWriter. Another very useful pre-defined variable is "request". It is of type javax.servlet.http.HttpServletRequest
A "request" in server-side processing refers to the transaction between a browser and the server. When someone clicks or enters a URL, the browser sends a "request" to the server for that URL, and shows the data returned. As a part of this "request", various data is available, including the file the browser wants from the server, and if the request is coming from pressing a SUBMIT button, the information the user has entered in the form fields.
The JSP "request" variable is used to obtain information from the request as sent by the browser. For instance, you can find out the name of the client's host (if available, otherwise the IP address will be returned.) Let us modify the code as shown:
<HTML> <BODY> <% // This scriptlet declares and initializes "date" System.out.println( "Evaluating date now" ); java.util.Date date = new java.util.Date(); %> Hello! The time is now <% out.println( date ); out.println( "<BR>Your machine's address is " ); out.println( request.getRemoteHost()); %> </BODY> </HTML>A similar variable is "response". This can be used to affect the response being sent to the browser. For instance, you can call response.sendRedirect( anotherUrl ); to send a response to the browser that it should load a different URL. This response will actualy go all the way to the browser. The browser will then send a different request, to "anotherUrl". This is a little different from some other JSP mechanisms we will come across, for including another page or forwarding the browser to another page. Exercise: Write a JSP to output the entire line, "Hello! The time is now ..." but use a scriptlet for the complete string, including the HTML tags.
JSP Directives
We have been fully qualifying the java.util.Date in the examples in the previous sections. Perhaps you wondered why we don't just import java.util.*;
It is possible to use "import" statements in JSPs, but the syntax is a little different from normal Java. Try the following example:<%@ page import="java.util.*" %> <HTML> <BODY> <% System.out.println( "Evaluating date now" ); Date date = new Date(); %> Hello! The time is now <%= date %> </BODY> </HTML>The first line in the above example is called a "directive". A JSP "directive" starts with <%@ characters. This one is a "page directive". The page directive can contain the list of all imported packages. To import more than one item, separate the package names by commas, e.g.
<%@ page import="java.util.*,java.text.*" %>There are a number of JSP directives, besides the page directive. Besides the page directives, the other most useful directives are include and taglib. We will be covering taglib separately. The include directive is used to physically include the contents of another file. The included file can be HTML or JSP or anything else -- the result is as if the original JSP file actually contained the included text. To see this directive in action, create a new JSP
<HTML> <BODY> Going to include hello.jsp...<BR> <%@ include file="hello.jsp" %> </BODY> </HTML>View this JSP in your browser, and you will see your original hello.jsp get included in the new JSP. Exercise: Modify all your earlier exercises to import the java.util packages.
implicit objects
JSP 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:
The request object provides methods to get HTTP header information including form data, cookies, HTTP methods etc.
We would see complete set of methods associated with request object in coming chapter: JSP - Client Request.
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.
We would see complete set of methods associated with response object in coming chapter: JSP - Server 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.
The session object is used to track client session between client requests. We would see complete usage of session object in coming chapter: JSP - Session Tracking.
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.
You can check a simple use of Application Object in chapter: JSP - Hits Counter
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:
This returns the servlet name, which is the string contained in the <servlet-name> element defined in the WEB-INF\web.xml file
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:
You can check a very good usage of pageContext in coming chapter: JSP - File Uploading.
The page object is really a direct synonym for the this object.
We would see complete usage of this object in coming chapter: JSP - Exception Handling.
JSP supports nine Implicit Objects which are listed below:
Object | Description |
---|---|
request | This is the HttpServletRequest object associated with the request. |
response | This is the HttpServletResponse object associated with the response to the client. |
out | This is the PrintWriter object used to send output to the client. |
session | This is the HttpSession object associated with the request. |
application | This is the ServletContext object associated with application context. |
config | This is the ServletConfig object associated with the page. |
pageContext | This encapsulates use of server-specific features like higher performance JspWriters. |
page | This is simply a synonym for this, and is used to call the methods defined by the translated servlet class. |
Exception | The 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.
We would see complete set of methods associated with request object in coming chapter: JSP - Client Request.
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.
We would see complete set of methods associated with response object in coming chapter: JSP - Server Response.
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.
Method | Description |
---|---|
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. We would see complete usage of session object in coming chapter: JSP - Session Tracking.
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.
You can check a simple use of Application Object in chapter: JSP - Hits Counter
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(); |
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.We would see complete usage of this object in coming chapter: JSP - Exception Handling.
JSP- Actions
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.
There is only one syntax for the Action element, as it conforms to the XML standard:
<jsp:action_name attribute="value" /> |
Syntax | Purpose |
---|---|
jsp:include | Includes a file at the time the page is requested |
jsp:include | Includes a file at the time the page is requested |
jsp:useBean | Finds or instantiates a JavaBean |
jsp:setProperty | Sets the property of a JavaBean |
jsp:getProperty | Inserts the property of a JavaBean into the output |
jsp:forward | Forwards the requester to a new page |
jsp:plugin | Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin |
jsp:element | Defines XML elements dynamically. |
jsp:attribute | Defines dynamically defined XML element's attribute. |
jsp:body | Defines dynamically defined XML element's body. |
jsp:text | Use to write template text in JSP pages and documents. |
Common Attributes:
There are two attributes that are common to all Action elements: the id attribute and the scope attribute.- Id attribute: The id attribute uniquely identifies the Action element, and allows the action to be referenced inside the JSP page. If the Action creates an instance of an object the id value can be used to reference it through the implicit object PageContext
- Scope attribute: This attribute identifies the lifecycle of the Action element. The id attribute and the scope attribute are directly related, as the scope attribute determines the lifespan of the object associated with the id. The scope attribute has four possible values: (a) page, (b)request, (c)session, and (d) application.
The <jsp:include> Action
This action lets you insert files into the page being generated. The syntax looks like this:<jsp:include page="relative URL" flush="true" /> |
Following is the list of attributes associated with include action:
Attribute | Description |
---|---|
page | The relative URL of the page to be included. |
flush | The boolean attribute determines whether the included resource has its buffer flushed before it is included. |
Example:
Let us define following two files (a)date.jps and (b) main.jsp as follows:Following is the content of date.jsp file:
<p> Today's date: <%= (new java.util.Date()).toLocaleString()%> </p> |
<html> <head> <title>The include Action Example</title> </head> <body> <center> <h2>The include action Example</h2> <jsp:include page="date.jsp" flush="true" /> </center> </body> </html> |
The include action ExampleToday's date: 12-Sep-2010 14:54:22 |
The <jsp:useBean> Action
The useBean action is quite versatile. It first searches for an existing object utilizing the id and scope variables. If an object is not found, it then tries to create the specified object.The simplest way to load a bean is as follows:
<jsp:useBean id="name" class="package.class" /> |
.
Following is the list of attributes associated with useBean action:
Attribute | Description |
---|---|
class | Designates the full package name of the bean. |
type | Specifies the type of the variable that will refer to the object. |
beanName | Gives the name of the bean as specified by the instantiate () method of the java.beans.Beans class. |
The <jsp:setProperty> Action
The setProperty action sets the properties of a Bean. The Bean must have been previously defined before this action. There are two basic ways to use the setProperty action:You can use jsp:setProperty after, but outside of, a jsp:useBean element, as below:
<jsp:useBean id="myName" ... /> ... <jsp:setProperty name="myName" property="someProperty" .../> |
A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as below:
<jsp:useBean id="myName" ... > ... <jsp:setProperty name="myName" property="someProperty" .../> </jsp:useBean> |
Following is the list of attributes associated with setProperty action:
Attribute | Description |
---|---|
name | Designates the bean whose property will be set. The Bean must have been previously defined. |
property | Indicates the property you want to set. A value of "*" means that all request parameters whose names match bean property names will be passed to the appropriate setter methods. |
value | The value that is to be assigned to the given property. The the parameter's value is null, or the parameter does not exist, the setProperty action is ignored. |
param | The param attribute is the name of the request parameter whose value the property is to receive. You can't use both value and param, but it is permissible to use neither. |
The <jsp:getProperty> Action
The getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts it into the output.The getProperty action has only two attributes, both of which are required ans simple syntax is as follows:
<jsp:useBean id="myName" ... /> ... <jsp:getProperty name="myName" property="someProperty" .../> |
Attribute | Description |
---|---|
name | The name of the Bean that has a property to be retrieved. The Bean must have been previously defined. |
property | The property attribute is the name of the Bean property to be retrieved. |
Example:
Let us define a test bean which we will use in our example:/* File: TestBean.java */ package action; public class TestBean { private String message = "No message specified"; public String getMessage() { return(message); } public void setMessage(String message) { this.message = message; } } |
Now use the following code in main.jsp file which loads the bean and sets/gets a simple String parameter:
<html> <head> <title>Using JavaBeans in JSP</title> </head> <body> <center> <h2>Using JavaBeans in JSP</h2> <jsp:useBean id="test" class="action.TestBean" /> <jsp:setProperty name="test" property="message" value="Hello JSP..." /> <p>Got message....</p> <jsp:getProperty name="test" property="message" /> </center> </body> </html> |
Using JavaBeans in JSPGot message....Hello JSP... |
The <jsp:forward> Action
The forward action terminates the action of the current page and forwards the request to another resource such as a static page, another JSP page, or a Java Servlet.The simple syntax of this action is as follows:
<jsp:forward page="Relative URL" /> |
Attribute | Description |
---|---|
page | Should consist of a relative URL of another resource such as a static page, another JSP page, or a Java Servlet. |
Example:
Let us reuse following two files (a) date.jps and (b) main.jsp as follows:Following is the content of date.jsp file:
<p> Today's date: <%= (new java.util.Date()).toLocaleString()%> </p> |
<html> <head> <title>The include Action Example</title> </head> <body> <center> <h2>The include action Example</h2> <jsp:forward page="date.jsp" /> </center> </body> </html> |
The <jsp:plugin> Action
The plugin action is used to insert Java components into a JSP page. It determines the type of browser and inserts the <object> or <embed> tags as needed.If the needed plugin is not present, it downloads the plugin and then executes the Java component. The Java component can be either an Applet or a JavaBean.
The plugin action has several attributes that correspond to common HTML tags used to format Java components. The <param> element can also be used to send parameters to the Applet or Bean.
Following is the typical syntax of using plugin action:
<jsp:plugin type="applet" codebase="dirname" code="MyApplet.class" width="60" height="80"> <jsp:param name="fontcolor" value="red" /> <jsp:param name="background" value="black" /> <jsp:fallback> Unable to initialize Java Plugin </jsp:fallback> </jsp:plugin> |
The <jsp:element> Action
The <jsp:attribute> Action
The <jsp:body> Action
The <jsp:element>, lt;jsp:attribute> and <jsp:body> actions are used to define XML elements dynamically. The word dynamically is important, because it means that the XML elements can be generated at request time rather than statically at compile time.Following is a simple example to define XML elements dynamically:
<%@page language="java" contentType="text/html"%> <html xmlns="http://www.w3c.org/1999/xhtml" xmlns:jsp="http://java.sun.com/JSP/Page"> <head><title>Generate XML Element</title></head> <body> <jsp:element name="xmlElement"> <jsp:attribute name="xmlElementAttr"> Value for the attribute </jsp:attribute> <jsp:body> Body for XML element </jsp:body> </jsp:element> </body> </html> |
<html xmlns="http://www.w3c.org/1999/xhtml" xmlns:jsp="http://java.sun.com/JSP/Page"> <head><title>Generate XML Element</title></head> <body> <xmlElement xmlElementAttr="Value for the attribute"> Body for XML element </xmlElement> </body> </html> |
The <jsp:text> Action
The <jsp:text> action can be used to write template text in JSP pages and documents. Following is the simple syntax for this action:<jsp:text>Template data</jsp:text> |
<jsp:text><![CDATA[<br>]]></jsp:text> |
<jsp:text><![CDATA[<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">]]> </jsp:text> <head><title>jsp:text action</title></head> <body> <books><book><jsp:text> Welcome to JSP Programming </jsp:text></book></books> </body> </html> |
JSP- Exceptional handling
JSP - Exception Handling
When you are writing JSP code, a programmer may leave a coding errors which can occur at any part of the code. You can have following type of errors in your JSP code:- Checked exceptions: Achecked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
- Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.
- Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
Using Exception Object:
The exception object is an instance of a subclass of Throwable (e.g., java.lang. NullPointerException) and is only available in error pages. Following is the list of important medthods available in the Throwable class.SN | Methods with Description |
---|---|
1 | public String getMessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor. |
2 | public Throwable getCause() Returns the cause of the exception as represented by a Throwable object. |
3 | public String toString() Returns the name of the class concatenated with the result of getMessage() |
4 | public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream. |
5 | public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack. |
6 | public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace. |
Following is an example to specifiy an error page for a main.jsp. To set up an error page, use the <%@ page errorPage="xxx" %> directive.
<%@ page errorPage="ShowError.jsp" %> <html> <head> <title>Error Handling Example</title> </head> <body> <% // Throw an exception to invoke the error page int x = 1; if (x == 1) { throw new RuntimeException("Error condition!!!"); } %> </body> </html> |
<%@ page isErrorPage="true" %> <html> <head> <title>Show Error Page</title> </head> <body> <h1>Opps...</h1> <p>Sorry, an error occurred.</p> <p>Here is the exception stack trace: </p> <pre> <% exception.printStackTrace(response.getWriter()); %> </pre> </body> </html> |
java.lang.RuntimeException: Error condition!!! ...... Opps... Sorry, an error occurred. Here is the exception stack trace: |
Using JSTL tags for Error Page:
You can make use of JSTL tags to write an error page ShowError.jsp. This page has almost same logic which we have used in above example, but it has better structure and it provides more information:<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@page isErrorPage="true" %> <html> <head> <title>Show Error Page</title> </head> <body> <h1>Opps...</h1> <table width="100%" border="1"> <tr valign="top"> <td width="40%"><b>Error:</b></td> <td>${pageContext.exception}</td> </tr> <tr valign="top"> <td><b>URI:</b></td> <td>${pageContext.errorData.requestURI}</td> </tr> <tr valign="top"> <td><b>Status code:</b></td> <td>${pageContext.errorData.statusCode}</td> </tr> <tr valign="top"> <td><b>Stack trace:</b></td> <td> <c:forEach var="trace" items="${pageContext.exception.stackTrace}"> <p>${trace}</p> </c:forEach> </td> </tr> </table> </body> </html> |
Opps...
|
Using Try...Catch Block:
If you want to handle errors with in the same page and want to take some action instead of firing an error page, you can make use of try....catch block.Following is a simple example which shows how to use try...catch block. Let us put following code in main.jsp:
<html> <head> <title>Try...Catch Example</title> </head> <body> <% try{ int i = 1; i = i / 0; out.println("The answer is " + i); } catch (Exception e){ out.println("An exception occurred: " + e.getMessage()); } %> </body> </html> |
An exception occurred: / by zero |
0 comments: