0% found this document useful (0 votes)
8 views

Java Server Pages-unit 4

Uploaded by

chandanaa0210
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Java Server Pages-unit 4

Uploaded by

chandanaa0210
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Java Server Pages

Java Server Pages (JSP) is a server-side technology that enables web programmers to generate web pages
dynamically in response to client requests. Among many server-side technologies used to build dynamic
web applications, JSP is the one that has grabbed the attention of web developers due to several reasons.
JSP is basically a high-level extension to the Java servlet technology. It enables inserting pure Java code
in an HTML document directly. These pages are executed under the supervision of an environment called
web container. The web container first compiles the page on the server and generates a servlet, which is
loaded in the Java Runtime Environment (JRE) automatically.
Need of JSP
It is used to create dynamic web content. It is a Web based technology helps us to create dynamic and
platform independent web pages. In this, Java code can be inserted in HTML/ XML pages or both.
JSP is first converted into servlet by JSP container before processing the client’s request
Benefits of JSP
JSP is still changing the overwhelming technical need to simplify application design. And it is
separating dynamic content from static templates displays data.
Some benefits of JSP technology are given below.
Role of web Application:
Utilizing JSP allows to simply the separate roles of web application or HTML designer from a
software developer.
Independent Technology:
The JSP is an independent technology platform because of its dynamic web pages content. And it also
contain web server and its underlying server components solutions.
Hassle free Platform:
No doubt, JSP pages perform perfectly without any hassle on any web platform. With the help of Java
Server Pages, the web developer feels free for web designs.
Easily Accessed:
The Java Server Pages can be accessed from any web server. Another is JSP runs on any web server
and web-enabled application server. One of the main reasons why the java server Pages interacts with
any web server is its dynamic behavior.
Reusable Technology:
The JSP technology is important for the use of reusable components. These components can be
combined or manipulated that is developing more purposeful components and enhance page designs.
Reduce development Time:
The JSP Technology definitely reduces development time because of its fast, secure, and apart from
the at development time. It provides more useful features to web designs.
BEA / IBM Sphere Server:
JSP is precompiled into Servlets at run time and executed by the JSP engine which is installed on a
web-enabled application server like as BEA web Logic / IBM Sphere. Because of this, JSP
technology is very different from Servlets.

Advantages of JSP
JSP vs. Active Server Pages (ASP)
The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual Basic or
other MS specific language, so it is more powerful and easier to use. Second, it is portable to other
operating systems and non-Microsoft Web servers.
JSP vs. Pure Servlets
It is more convenient to write (and to modify!) regular HTML than to have plenty of println
statements that generate the HTML.
JSP vs. Server-Side Includes (SSI)
SSI is really only intended for simple inclusions, not for "real" programs that use form data, make
database connections, and the like.
JSP vs. JavaScript
JavaScript can generate HTML dynamically on the client but can hardly interact with the web server
to perform complex tasks like database access and image processing etc.
JSP vs. Static HTML
Regular HTML, of course, cannot contain dynamic information.

WORKING OF JSP
Java Server Pages are made operable by contents (HTML tags, JSP tags and scripts) translated
into a servlet by the application server. This process is responsible for translating both the
dynamic and static elements declared within the JSP file into Java servlet code that delivers the
translated contents through the Web server output stream to the browser. Because JSPs are
server-side technology, the processing of both, the static and dynamic elements of the page,
occurs in the server. The architecture of a JSP/servlet enabled web site is often referred to as thin-
client because most of the business logic is executed on the server.
The web browser makes a request to the JSP page.
•The JSP engine parses the contents of the JSP file.
•The JSP engine creates temporary servlet source code based on the contents of the JSP. The
generated servlet is responsible for rendering the static elements of the JSP specified at design
time in addition to creating the dynamic elements of the page.
•The servlet source code is compiled by the Java compiler into a servlet class file.
•The servlet is instantiated. The init and service methods of the servlet are called and the servlet
logic is executed.
• The combination of static HTML and graphics combined with the dynamic elements specified
in the original JSP page definition are sent to the Web browser through the output stream of the
servlet’s response object.

JSP SYNTAX
The syntax of JSP is similar to that of XML. All JSP tags must conform to the following general
rules:
• Tags must have their matching end tags.
• Attributes must appear in the start tag.
• Attribute values in the tag must be quoted.
White spaces within the body text of a JSP page are preserved during the translation phase. To
use
special characters such as ‘%’, add a ‘\’ character before it. To use the ‘\’ character, add another
‘\’ character before it
CREATING A SIMPLE JSP PAGE
The following are the steps involved in creating a JSP file in Netbeans IDE.
1. Open Netbeans IDE, Select File ->New Project
2. Select Java Web ->Web Application and then click on Next
3. Give a name to the project and click on Next
4. Select the Server GlassFish and click Finish
5. The complete directory structure required for JSP Application will be created automatically
by the IDE. A default index.jsp file is created under the folder Web Pages.
6. To create a JSP file, right-click on Web Pages folder, -> select New ->JSP option.
7. Give a file name as shown below and click Finish.
8. Write some code with JSP syntax in the created file.

9. To run the file, right-click on the jsp file created and select Run option.

COMPONENTS OF JAVA SERVER PAGES


Java Server Pages are composed of standard HTML tags and JSP tags. A JSP page consists of
the following components:
• Directives
• Scripting Elements
o Declarations
o Expressions
o Scriptlets
• Actions
JSP tag Meaning

<%@...-%> Used for JSP directives such as page and include.


<%!...%> Used for variables, methods, and inner class declarations.
<%=...%> Used for JSP expressions.
<%...%> Used for JSP scriptlets that can contain arbitrary Java statements.

DIRECTIVES

A JSP directive is a global definition sent to the JSP engine that remains valid regardless of
any specific requests made to the JSP page. A directive always appears at the top of the JSP
file, before any other JSP tags.
They are enclosed within the <%@ and %> tags. The commonly used directives are page,
include, and taglib.
The syntax of a directive is:
<%@ directive directive_attr_name = value %>

page directive
The page directive defines page dependent attributes to the JSP engine. The page directive
has many attributes, which can be specified in any order. The following is the syntax of the
page directive:
<%@ page language=”java” buffer=”none”
isThreadSafe=”yes” errorPage=”/error.jsp” %>

import
The value of this attribute is a list of fully qualified names of classes separated by commas (,),
to be imported by the JSP file. To import all the classes of a package, use “.*” at the end of
the package name.
The following directive imports all the classes in the java.io and java.reflect packages and the
class vector that belongs to the java.util package.
<%@ page import=“java.io.*, java.reflect.*, java.util.Vector” %>

session
This attribute indicates whether the JSP file requires an HTTP session. The following syntax
is used:
session=”true | false”
If true is specified (this is the default value), the JSP file has a session object that refers to the
current or new session. If the value is false, no session object is created. If the JSP file does
not require a session, the value should be set to false for performance considerations.

buffer
Syntax:
buffer=”none | sizekb”
The buffer attribute indicates the size in kilobytes (default is 8kb) of the output buffer to be
used by the JSP file. The value ‘none’ indicates a buffer with zero size. In such a case, the
output is written directly to the output stream of the response object of the servlet.
autoFlush
Syntax: autoFlush=”true | false”
• The autoFlush attribute specifies whether the buffer should be flushed automatically
when it is full.
• If set to false, a buffer overflow exception is thrown when the buffer becomes full.
The default value is true. The value of autoFlush can never be set to false when the
buffer is set to none.

isThreadSafe
Syntax: isThreadSafe=”true | false” This attribute indicates whether the JSP page can handle
multiple threads simultaneously.
• If set to true, the JSP container is allowed to send multiple concurrent client requests
to this JSP page. This is to make ensure that the access to shared resources by
multiple concurrent threads is effectively synchronized.
• If set to false, the JSP container sends clients’ requests one by one using a single
thread. This attribute basically provides information to the underlying servlet on
whether it should implement the SingleThreadModel interface or not.

info
Syntax: info=”text” It allows the programmer to specify descriptive information about the
JSP page. This information can be retrieved using the Servlet.getServletInfo() method.

contentType
Syntax: contentType=”MIMEType [ ;charset=characterSet ]”
It specifies the MIME type and encoding used in the generated response to be sent to the
client. MIME types and encoding supported by the JSP container can only be specified.

errorPage and isErrorPage


Syntax: errorPage=”relativeURL” isErrorPage=”true | false”
When an uncaught exception occurs in a JSP page, the JSP container sends information
explaining the exception, which is undesirable for some cases such as commercial sites. The
errorPage attribute specifies the relative path name of another JSP page to be displayed, in
case an error occurs in the current page. In the error page, the isErrorPage attribute must be
set to true.

include directive
This directive inserts the contents of a file in a JSP page, during the translation phase when
the JSP page
is compiled.
Syntax:
<%@ include file=”relativeURL” %>
If the file to be included is an HTML or text file, its contents are directly included in the place
of the
include directive. The following example includes an HTML file header.html in a JSP page.
<%@ include file=”header.html” %>
Comments
Comments are used to document the JSP pages and can be inserted anywhere in the JSP page.
The
general syntax is as follows:
<%-- JSP comment --%>
Anything between <%-- and --%> is ignored by the JSP engine and is not even added to the
servlet’s
source code. For example:
<%-- Prints current date and time --%>
<%= new java.util.Date(); %>

taglib
The taglib directive allows custom extensions to be made to the tags known to the JSP
engine. The JSP
taglib directive is used to define a tag library that defines many tags. Programmers use the
TLD (Tag
Library Descriptor) file to define the tags.
Syntax
<%@ taglib uri=”uritaglibrary” prefix=”prefixtaglibrary” %>

SCRIPTING ELEMENTS
The scripting elements provide the ability to insert java code in the JSP. There are three types
of scripting elements:
• scriptlet tag
• expression tag
• declaration tag
Scriptlets
JSP supports embedding of Java code fragments within a JSP by using a scriptlet block.
Scriptlets are used to embed small code blocks within the JSP page, rather than to declare
entire methods as in a declarations block.
The syntax for a scriptlet is:
<% scriptlet %>
The following example uses a scriptlet to output an HTML message based on the time of day.
The HTML elements appear outside the script declarations.
<% if (Calendar.getInstance().get(Calendar.AM_PM) == Calendar.AM)
{%>
How are you this morning ?
<% } else
{ %>
How are you this afternoon ?
<% } %>
In the following example, two files have been created, index.html and welcome.jsp. The
index.
html file gets the username from the user and the welcome.jsp file prints the username with
the welcome message.
//index.html
<html>
<body>
<form action=”welcome.jsp”>
<input type=”text” name=”uname”>
<input type=”submit” value=”go”><br/>
</form>
</body>
</html>
//welcome.jsp
<html>
<body>
<%
String name=request.getParameter(“uname”);
out.print(“welcome “+name);
%>
</form>
</body>
</html>
Expressions
Expressions are scriptlet fragments whose results can be converted to String objects and subsequently
fed to the output stream for display in a browser. They are generally used to insert a small piece of data in
a JSP page, without using the out.print() or out.write() statements. It is a faster, easier, and clearer
way to display the values of variables/parameters/expressions in a JSP page. The general syntax of JSP
expressions is as follows:
<%= expressions %>
The expression is embedded within the tag pair <%= and %>. There is no semicolon at the end of
the expression. The expression is evaluated, converted to a String and inserted in place of the expression
using an out.print() statement. For example, to add 3 and 4 and display the result, the programmer
must write the JSP expression as follows:
3 + 4 = <%= 3+4 %>
The expression is translated into the following Java statements in servlet source code.
out.write(“3 + 4 = “);
out.print( 3+4 );
The following output is displayed:
3+4=7
The expression can be anything, as long as it can be converted to a string. For example, the following
expression uses a java.util.Date object.
Date and time is : <%= new java.util.Date() %>

Declarations
A declaration block contains Java variables and methods that are called from an expression block within
the JSP file. The code within a declaration block is usually written in Java, and is often used for additional
processing on the dynamic data generated by a JavaBeans property. The syntax of a declaration is:
<%! declarations %>
For example :
<%! int sum = 0; %>
<%! int x, y , z; %>
<%! java.util.Hashtable table = new java.util.Hashtable();%>
These variable declarations are inserted into the body of the Servlet class, that is outside the _jsp-
Service() method that processes the client requests. So, variables declared in this way become instance
variables of the underlying servlet.
<%! int sum = 0; %>
The following is an example of JSP declaration tag, where a method is defined which returns the cube
of given number, this method is called from the JSP expression tag.
// index.jsp
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= “Cube of 3 is:”+cube(3) %>
</body>
</html>

JSP STANDARD ACTIONS


There are many JSP action tags or elements. Each JSP action tag is used to perform some specific tasks.
The action tags are used to control the flow between pages and to use JavaBeans. Table 19.2 gives a list
of JSP action tags.

Table 19.2 JSP action tags


JSP Action Tags Description

jsp:forward forwards the request and response to another resource.

jsp:include includes another resource.


jsp:useBean creates or locates a bean object.
jsp:setProperty sets the value of property in the bean object.
jsp:getProperty prints the value of property of the bean.
jsp:plugin embeds another components such as an applet.
jsp:param sets the parameter value. It is used mostly in forward and include.

jsp:fallback can be used to print the message if plugin is working. It is used in jsp:plugin.

include
This action tag provides an alternative way to include a file in a JSP page. The general syntax of the
include action tag is:

<jsp:include page=”relativeURL | <%=expression%>” flush=”true” />

For example, the following code includes the file header.jsp in the current page:

<jsp:include page=”header.jsp” />

It is similar to the include directive but instead of inserting the text of the included file in the original file at compilation time, it actually
includes the target at run-time. It acts like a subroutine where the control is passed temporarily to the target. The control is then returned
to the original JSP page. The result of the included file is inserted in the place of <jsp:include> action in the original JSP page.
param
The JSP <jsp:param> action allows the programmer to append additional parameters to the current
request. The general syntax is as follows:

<jsp:param name=”parameterName”
value=”parameterValue | <%=expression%>” />

The name and value attributes of the <jsp:param> tag specify the case sensitive name and value of
the parameter, respectively. It is typically used with the <jsp:include> and <jsp:forward> action tags.
For example, the following code passes the control to the JSP page process.jsp temporarily, with two
additional parameters, user and sessionId.

<jsp:include page=”process.jsp”>
<jsp:param name=”user” value=”monali” />
<jsp:param name=”sessionId” value=”12D43F3Q436N43” />
</jsp:include>

forward
This action tag hands over the current request to the specified page internally at the server side. If the
current page has already generated some output, it is suppressed. The output will only be caused by the
page that has handled the request last in the forward chain. The control is never returned to the original
page. The general syntax of the JSP forward action tag is

<jsp:forward page=”relativeURL | <%=expression%>” />

plugin
The <jsp:plugin> action is used to generate an HTML file that can download the Java plug-in on
demand and execute applets or JavaBeans. It is an alternative way to deploy applets through the Java
plug-in. Since JSP pages are dynamic in nature, the developers of web applications can make use of the
Java plug-in to generate browser-specific tags to insert applets on the fly in a much easier and flexible
way. The <jsp:plugin> action generates the embed or object tag for the applet to be executed, depend-
ing upon the browser used. When the JSP is translated, the <jsp:plugin> action element is substituted
by either an <embed> or an <object> HTML tag. The following code specifies an applet.

<jsp:plugin type=”applet” code=”Message” >


<jsp:params>
<jsp:param name=”message” value=”Hello World!”/>
</jsp:params>
<jsp:fallback>
<p> Unable to start Plug-in. </p>
</jsp:fallback>
</jsp:plugin>

jsp:useBean
The jsp:useBean tag is used to declare a JavaBean object to use within the JSP. This declaration
must be done before using the jsp:getProperty and jsp:setProperty tags. When the jsp:use-
Bean tag is processed, the application server performs a lookup of the specified given Java object
using the values specified in the id and scope attributes. If the object is not found, it will attempt
to create it using the values specified in the scope and class attributes. The syntax for inserting a
JavaBean is:

<jsp:useBean id=”beanInstanceName”
scope=”page|request|session|application”
typespec>
optional scriptlets and tags
</jsp:useBean>
jsp:getProperty
Once the bean has been declared with jsp:useBean, the programmer can access its exposed properties
through the jsp:getProperty tag, which inserts the String value of the primitive type or object into the
output stream. For primitive types, the conversion to String is performed automatically. For object types,
the toString method of the object is called. The syntax for the jsp:getProperty tag is:

<jsp:getProperty name=”beanName” property=”propertyName”/>

jsp:SetProperty
The properties of beans can be set by using the jsp:setProperty tag. The syntax for this tag is:

<jsp:setProperty name=”beanName” prop_expr/>

IMPLICIT OBJECTS
Web container allows a programmer to directly access many useful objects defined in the _jspSer-
vice() method of the JSP page’s underlying servlet. These objects are called implicit objects as they
are instantiated automatically. The implicit objects contain information about request, response, session,
configuration, etc. Some implicit objects are described in Table 19.3. The following code snippet is an
example of accessing the out implicit object to display a line of text in the browser:

out.println(“Here is the <b>Date Display JSP</b>”);

Table 19.3 JSP implicit objects


Variable Class Description
out javax.servlet.jsp.JspWriter Output stream of the JSP page’s servlet.
request Subtype of javax.servlet. Current client request being handled by the JSP page.
ServletRequest
response Subtype of javax.servlet. Response generated by the JSP page to be returned to the client.
ServletResponse

config javax.servlet.ServletConfig Initialization information of the JSP page’s servlet.


session javax.servlet.http.HttpSession Session object for the client.
application javax.servlet.ServletContext Context of the JSP page’s servlet and other web components
contained in the same application.
exception java.lang.Throwable Represents error. Accessible only from an error page.
page java.lang.Object Refers to JSP page’s servlet processing the current request.
pageContext javax.servlet.jsp.PageContext The context of the JSP page that provides APIs to manage
the various scoped attributes. It is extensively used by the tag
handlers.
request
This object refers to the javax.servlet.http.HttpServletRequest type object that is passed to the
_jspService() method of the generated servlet. It represents the HTTP request made by a client to this
JSP page. It is used to retrieve information sent by the client such as parameters (using the getParam-
eter() method), HTTP request type (GET, POST, HEAD, etc), and HTTP request headers (cookies,
referrer, etc). This implicit object has request scope.

<%
String name = request.getParameter(“name”);
out.println(“Hello “ + name);
%>

response
This object refers to the javax.servlet.http.HttpServletResponse type object that is passed to the
_jspService() method of the generated servlet. It represents the HTTP response to the client. This
object is used to send information such as HTTP response header and cookies. This implicit object has
page scope.

pageContext
This javax.servlet.jsp.PageContext type object refers to the current JSP page context. It is used to
access information related to this page such as request, response, session, application, and underlying
servlet configuration. This implicit object has page scope.

session
This javax.servlet.http.HttpSession type object refers to the session used by the JSP page. There is
no session object is created if the session attribute of the page directive is turned off and any attempt
to refer to this object causes an error. It is used to access session-related information such as creation
time and ID associated with this session. This implicit object has session scope.
application
This javax.servlet.ServletContext object refers to the underlying application and is used to share
data among all pages under this application. This implicit object has application scope.

out
It denotes the character output stream that is used to send data back to the client. It is a buffered version
of java.io.PrintWriter called javax.servlet.jsp.JspWriter type object. The object out is used
only in scriptlets. This implicit object has page scope.

<% out.println(“Hello World!”); %>

JSP expressions are placed in the output stream automatically and hence do not use this out object
there explicitly.

config
This javax.servlet.ServletConfig type object refers to the configuration of the underlying servlet. It
is used to retrieve initial parameters, servlet name, etc. This implicit object has page scope.

page
This object refers to the JSP page itself. It can be used to call any instance of the JSP page’s servlet. This
implicit object has page scope.

exception
This represents an uncaught exception, which causes an error page to be called. This object is available
in the JSP page for which the isErrorPage attribute of the page directive is set to true. This implicit
object has page scope.

You might also like