unit 5 jsp
unit 5 jsp
Welcome.jsp:-
<html>
<body>
<%! Int a=5;
Int fun(int k)
{
return k*a;
}
%>
<%= “7 multiple by 5 is”+fun(7)%>
</body>
</html>
Expression
Contains an expression valid in the scripting language
used in the JSP page.
JSP Syntax
<%= expression %>
XML Syntax
<jsp:expression> expression </jsp:expression>
Description
An expression element contains a scripting language
expression that is evaluated, converted to a String, and
inserted into the response where the expression
appears in the JSP page. Because the value of an
expression is converted to a String, you can use an
expression within a line of text, whether or not it is
tagged with HTML, in a JSP page.
Example
Welcome, <%=userName%>
Output:
Expression
<%= new java.util.Date()%>
When this is generated into servlet code, the resulting
java stmt will probably look like this:
out.print(new java.util.Date());
Out is an instance of javax.servlet.http.jsp.JspWriter and it
is associated with the response for the generated
servlet.
Cotents of your jsp expression are used directly as the
parameter to the print() method.so it must not end with
semicolon.
JSP expression tag
• It is mainly used to print the values of variable or method.
• <%= statement to be written on output stream %> or
alternatively you can use :-
<jsp:expression> expression </jsp:expression>
Welcome.html:-
<html>
<body> Welcome.jsp:-
<form action="welcome.jsp"> <html>
<input type="text" name="uname"> <body>
<input type="submit" value="go"> <%= “welcome”+request.getParameter(“uname”)%>
<br/>
</form> </body>
</body> </html>
</html>
Script lets
Contains a code fragment valid in the page scripting
language.
Scriptlets allows you to include a series of java statements
inside the _jspService method that are executed on
every request to the page.these java stmts are
incorporated into _jspService method as it is.so you
must terminate them with semicolon.
JSP Syntax
<% code fragment %>
OR
<jsp:scriptlet> code fragment </jsp:scriptlet>
• A scriptlet JSP scriptlet tag
tag is used to execute java source
code in JSP
– Syntax:
<% java source code %>
Welcome.html:- Welcome.jsp:-
<html> <html>
<body> <body>
<form action="welcome.jsp"> <%
<input type="text" name="uname"> String name=request.getParameter(“uname”);
<input type="submit" value="go"> Out.print(“welcome”+name);
<br/> %>
</form>
</body> </body>
</html> </html>
Comments
To denote any lines you want to be completely ignored by
the JSP translation process.
Example
<%-- Author: James Gosling --%>
JSP Implicit Objects
• There are 9 jsp implicit objects. These objects
are created by the web container that are
available to all the jsp pages.
• A list of the 9 implicit objects is given below:
Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
1) JSP out implicit object
</body>
</html>
JSP request object
• It can be used to get request information such as parameter,
header information, remote address, server name, server port,
content type, character encoding etc.
• It can also be used to set, get and remove attributes from the
jsp request scope.
Welcome.html:- Welcome.jsp:-
<html> <html>
<body> <body>
<form action="welcome.jsp"> <%
<input type="text" name="uname String
"> name=request.getParameter(“uname”);
<input type="submit" value="go" Out.print(“welcome”+name);
> %>
<br/>
</form> </body>
</body> </html>
</html>
The response Object:
• It can be used to add or manipulate response
such as redirect response to another resource,
send error etc.
Welcome.html:- Welcome.jsp:-
<html> <html>
<body> <body>
<form action="welcome.jsp"> <%
<input type="text" name="uname response.sendRedirect(“http://
"> google.com”)
<input type="submit" value="go" %>
>
<br/> </body>
</form> </html>
</body>
</html>
Application Object
• Any attribute set by application implicit
object would be available to all the JSP pages.
• It is different from session
• It’s mostly used methods are:-
• Integer counter = (Integer)application.getAttribute(“Visit");
• application.setAttribute(“Visit”, counter);
<%@ page import="java.io.*,java.util.*" %>
<html> <head> <title>Application Implicit Object Example</title> </head>
<body>
<%
Integer counter= (Integer)application.getAttribute("numberOfVisits");
if( counter ==null || counter == 0 )
{
counter = 1;
}
else
{
counter = counter+ 1;
}
application.setAttribute("numberOfVisits", counter);
%>
<h3>Total number of hits to this Page is: <%= counter%></h3>
</body>
</html>
Session Object
Welcome.html:- Welcome.jsp:-
<html> <html>
<body> <body>
<form action="welcome.jsp"> <%
<input type="text" name="uname"> String
<input type="submit" value="go"> name=request.getParameter(“uname”);
<br/> session.setAttribute("user“, name); %>
</form> <a href=“second.jsp”>second page</a>
</body> </body>
</html> </html>
Second.jsp:-
<html>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
JSP Directives
Directives are instructions to jsp compiler.
Those intructions tell the compiler that some
action needs to be taken.
General syntax for directives is:
<%@ Directive-name attribute-value pairs %>
There are three main directives defined in jsp:
• Page
• Include
• Taglib
Page Directive
Page Directive- Defines attributes that apply to an entire
JSP page.
JSP Syntax
<%@ page attribute=“value” attribute=“value” … %>
OR
<jsp:directive.page pageDirectiveAttrList />
where pageDirectiveAttrList is the same as the list in
the JSP syntax.
XML Syntax
<jsp:directive.page pageDirectiveAttrList /> where
pageDirectiveAttrList is the same as the list in the JSP
syntax.
Examples
<%@ page import="java.util.*, java.lang.*" %>
<jsp:directive.page errorPage="error.jsp" />
Page Directive
Description
• The page directive applies to an entire JSP page and
any of its static include files, which together are called
a translation unit. A static include file is a file whose
content becomes part of the calling JSP page. The page
directive does not apply to any dynamic resources; see
<jsp:include> for more information.
• You can use the page directive more than once in a
translation unit, but you can only use each attribute,
except import, once. Because the import attribute is
similar to the import statement in the Java
programming language, you can use a page directive
with import more than once in a JSP page or
translation unit.
• No matter where you position the page directive in a
JSP page or included files, it applies to the entire
translation unit. However, it is often good programming
style to place it at the top of the JSP page.
Page Directive
• Attributes
• language="java"
– The scripting language used in scriptlets, declarations, and
expressions in the JSP page and any included files. In v2.0, the
only allowed value is java.
• extends="package.class"
– The fully qualified name of the superclass of the Java class this
JSP page will be compiled to. Use this attribute cautiously, as it
can limit the JSP container's ability to provide a specialized
superclass that improves the quality of the compiled class.
Page Directive
• import="{package.class | package.*}, ..."
– A comma-separated list of Java packages that the JSP page should
import. The packages (and their classes) are available to scriptlets,
expressions, and declarations within the JSP page. If you want to
import more than one package, you can specify a comma-
separated list after import or you can use import more than once in
a JSP page.
– The following packages are implicitly imported, so you don't need
to specify them with the import attribute:
– java.lang.*
– javax.servlet.*
– javax.servlet.jsp.*
– javax.servlet.http.*
– You must place the import attribute before the element that calls
the imported class.
Page Directive
• isThreadSafe="true|false"
– Whether thread safety is implemented in the JSP page. The default
value is true, which means that the JSP container can send
multiple, concurrent client requests to the JSP page. You must
write code in the JSP page to synchronize the multiple client
threads. If you use false, the JSP container sends client requests
one at a time to the JSP page.
• info="text"
– A text string that is incorporated verbatim into the compiled JSP
page. You can later retrieve the string with the
Servlet.getServletInfo() method.
• errorPage="relativeURL"
– A pathname to a JSP page that this JSP page sends exceptions to.
If the pathname begins with a /, the path is relative to the JSP
application's document root directory and is resolved by the web
server. If not, the pathname is relative to the current JSP page.
Page Directive
• isErrorPage="true|false"
– Whether the JSP page displays an error page. If set to true, you can use
the exception object in the JSP page. If set to false (the default value), you
cannot use the exception object in the JSP page.
• pageEncoding="characterSet | ISO-8859-1"
– The character encoding the JSP page uses for the response. The default
character set is ISO-8859-1.
Include Directive
Includes a static file in a JSP page, parsing the file's JSP elements.
JSP Syntax
<%@ include file="relativeURL" %> OR
<jsp:directive.include file="relativeURL" />
XML Syntax
<jsp:directive.include file="relativeURL" />
Examples
include.jsp:
<html>
<head>
<title>An Include Test</title>
</head>
<body bgcolor="white">
<font color="blue">
The current date and time are <%@ include file="date.jsp" %>
</font> </body> </html>
Include Directive
date.jsp
<%@ page import="java.util.*" %>
<%= (new java.util.Date() ).toLocaleString() %>
Displays in the page: The current date and time are Aug 30, 1999 2:38:40
Description
An include directive inserts a file of text or code in a JSP page at
translation time, when the JSP page is compiled. When you use the
include directive, the include process is static. A static include means
that the text of the included file is added to the JSP page. The included
file can be a JSP page, HTML file, XML document, or text file. If the
included file is a JSP page, its JSP elements are translated and
included (along with any other text) in the JSP page. Once the
included file is translated and included, the translation process
resumes with the next line of the including JSP page.
Include Directive
Attributes
file="relativeURL"
– The pathname to the included file, which is always a relative URL.
A relative URL is just the path segment of an URL, without a
protocol, port, or domain name, like this:
– "error.jsp" "/templates/onlinestore.html" "/beans/calendar.jsp"
– If the relative URL starts with /, the path is relative to the JSP
application's context, which is a javax.servlet.ServletContext
object that is in turn stored in the application object. If the relative
URL starts with a directory or file name, the path is relative to the
JSP page.
taglib directive
Defines a tag library and prefix for the custom tags used in the JSP page.
JSP Syntax
<%@ taglib uri="URI“ prefix="tagPrefix" %>
Examples
<%@ taglib uri="http://www.jspcentral.com/tags" prefix=“abc" %>
Attributes
• uri="URI"-
The Uniform Resource Identifier (URI) that uniquely
locates the TLD that describes the set of custom tags
associated with the named tag prefix.
• Prefix=‘tagprefix’
The prefix that precedes the custom tag name, for
example, public in <public:loop>. Empty prefixes are
illegal.
If you are developing or using custom tags, you cannot
use the tag prefixes jsp, jspx, java, javax, servlet, sun,
and sunw, as they are reserved by Sun Microsystems.
JSP ACTIONS
Servlet container provides many built in functionality to ease the
development of the applications
Programmers can use these functions in JSP applications. The JSP
Actions tags enables the programmer to use these functions. The JSP
Actions are XML tags that can be used in the JSP page.
Here is the list of JSP Actions:
jsp:forward
The jsp:forward tag is used to forward the request and response to
another JSP or servlet. In this case the request never return to the
calling JSP page. (internally uses RequestDispatcher forward()
method)
jsp:param/ jsp:params
The jsp:param action is used to add the specific parameter to current
request. The jsp:param tag can be used inside a jsp:include,
jsp:forward or jsp:params block.
JSP ACTIONS
jsp:include
The jsp:include action work as a subroutine, the Java servlet
temporarily passes the request and response to the specified
JSP/Servlet. Control is then returned back to the current JSP page.
jsp:useBean
The jsp:useBean tag is used to instantiate an object of Java Bean or it
can re-use existing java bean object.
jsp:getProperty
The jsp:getPropertyB is used to get specified property from the
JavaBean object.
jsp:setProperty
The jsp:setProperty tag is used to set a property in the JavaBean
object.
jsp:forward
Forwards a request to a web resource.
JSP Syntax
<jsp:forward page="{relativeURL | <%= expression %>}" />
or
<jsp:forward page="{relativeURL | <%= expression %>}" >
<jsp:param name="parameterName" value="{parameterValue | <%=
expression %>}" />
</jsp:forward>
Examples
<jsp:forward page="/servlet/login" />
<jsp:forward page="/servlet/login">
<jsp:param name="username" value="jsmith" />
</jsp:forward>
jsp:forward
• The <jsp:forward> element forwards the request object containing the client
request information from one JSP page to another resource.
• The target resource can be an HTML file, another JSP page, or a servlet, as
long as it is in the same application context as the forwarding JSP page. The
lines in the source JSP page after the <jsp:forward> element are not processed.
• You can pass parameter names and values to the target resource by using a
<jsp:param> clause. An example of this would be passing the parameter name
username (with name="username") and the value scott (with value="scott") to
a servlet as part of the request. If you use <jsp:param>, the target resource
should be a dynamic resource that can handle the parameters.
Attributes
page="{relativeURL | <%= expression %>}"
– A String or an expression representing the relative URL of the component
to which you are forwarding the request. The component can be another
JSP page, a servlet, or any other object that can respond to a request.
– The relative URL looks like a path--it cannot contain a protocol name,
port number, or domain name. The URL can be absolute or relative to the
current JSP page. If it is absolute (beginning with a /), the path is resolved
by your web or application server.
jsp:param/params
• <jsp:param>
When a request is forwarded from one JSP to another then automatically request
parameters are also forwarded to another JSP.
For Example:
<jsp:param name=“email” value=“a@b.com”/>
• <jsp:params>
If more than one <jsp:param> tag is used then we should put them in
<jsp:params> tag.
For Example:
<jsp:params>
<jsp:params name=“email” value=“a@b.com”/>
<jsp:params name=“hobby” value=“reading”/>
</jsp:params>
jsp:include
Includes a static file or the result from another web component.
JSP Syntax
<jsp:include page="{relativeURL | <%= expression %>}" />
or
<jsp:include page="{relativeURL | <%= expression %>}" />
<jsp:param name="parameterName" value="{parameterValue | <
%= expression %>}" />
</jsp:include>
jsp:include
• The <jsp:include> element allows you to include either a static or
dynamic resource in a JSP page. The results of including static and
dynamic resources are quite different. If the resource is static, its
content is included in the calling JSP page. If the resource is dynamic,
it acts on a request and sends back a result that is included in the JSP
page. When the include action is finished, the JSP container continues
processing the remainder of the JSP page.
• You cannot always determine from a pathname if a resource is static or
dynamic. For example, http://server:8080/index.html might map to a
servlet through a server alias. The <jsp:include> element handles both
types of resources, so it is convenient to use when you don't know
whether the resource is static or dynamic.
• If the included resource is dynamic, you can use a <jsp:param> clause
to pass the name and value of a parameter to the resource. As an
example, you could pass the string username and a user's name to a
login form that is coded in a JSP page.
jsp:useBean
Locates or instantiates a bean with a specific name and scope.
JSP Syntax
<jsp:useBean id="beanInstanceName" scope="page|request|session|
application"
{
class="package.class" [ type="package.class“ ]|
beanName="{package.class | <%= expression %>}“
type="package.class" |
}
{ /> | > other elements </jsp:useBean> }
jsp:useBean
Examples
<jsp:useBean id="cart" scope="session" class="session.Carts" />
<jsp:setProperty name="cart" property="*" />
• type="package.class"
– If the bean already exists in the scope, gives the bean a data type
other than the class from which it was instantiated. The value of
type must be a superclass of class or an interface implemented by
class.
– If you use type without class or beanName, no bean is instantiated.
The package and class name are case sensitive.
jsp:useBean
• class="package.class" type="package.class"
– Instantiates a bean from the class named in class and assigns the
bean the data type you specify in type. The value of type can be
the same as class, a superclass of class, or an interface
implemented by class.
– The class you specify in class must not be abstract and must have a
public, no-argument constructor. The package and class names you
use with both class and type are case sensitive.
jsp:setProperty
Sets a property value or values in a bean.
JSP Syntax
<jsp:setProperty name="beanInstanceName"
{ property="*" | property="propertyName"
[ param="parameterName" ] | property="propertyName"
value="{stringLiteral| <%= expression %>}" }
/>
Examples
<jsp:setProperty name="mybean" property="*" />
<jsp:setProperty name="mybean" property="username" />
<jsp:setProperty name="mybean" property="username" value="Steve" />
jsp:setProperty
Description
The <jsp:setProperty> element sets the value of one or more properties in
a bean, using the bean's setter methods. You must declare the bean
with <jsp:useBean> before you set a property value with
<jsp:setProperty>. Because <jsp:useBean> and <jsp:setProperty>
work together, the bean instance names they use must match (that is,
the value of name in <jsp:setProperty> and the value of id in
<jsp:useBean> must be the same).
You can use <jsp:setProperty> to set property values in several ways:
• By passing all of the values the user enters (stored as parameters in the
request object) to matching properties in the bean
• By passing a specific value the user enters to a specific property in the
bean
• By setting a bean property to a value you specify as either a String or
an expression that is evaluated at runtime
Each method of setting property values has its own syntax, as described in
the next section.
jsp:setProperty
• Attributes and Usage
• name="beanInstanceName"
– The name of an instance of a bean that has already been created or
located with a <jsp:useBean> element. The value of name must
match the value of id in <jsp:useBean>. The <jsp:useBean>
element must appear before <jsp:setProperty> in the JSP page.
• property="*"
– Stores all of the values of request parameters in bean properties.
The names of the bean properties must match the names of the
request parameters. A bean property is usually defined by a
variable declaration with matching getter and setter methods
jsp:setProperty
• property="propertyName" [ param="parameterName" ]
– Sets one bean property to the value of one request parameter. In the
syntax, property specifies the name of the bean property and param
specifies the name of the request parameter by which data is being sent
from the client to the server.
– If the bean property and the request parameter have different names, you
must specify both property and param. If they have the same name, you
can specify property and omit param.
– If a parameter has an empty or null value, the corresponding bean
property is not set.
• property="propertyName" value="{string | <%= expression %>}"
– Sets one bean property to a specific value. The value can be a String or an
expression that is evaluated at runtime. If the value is a String, it is
converted to the bean property's data type according to the conversion
rules shown above in TABLE 1. If it is an expression, its value must have
a data type that matches the the data type of the value of the expression
must match the data type of the bean property.
jsp:getProperty
Inserts the value of a bean property into the result.
JSP Syntax
<jsp:getProperty name="beanInstanceName"
property="propertyName" />
XML Syntax
<jsp:getProperty name="beanInstanceName"
property="propertyName" />
Examples
<jsp:useBean id="calendar" scope="page" class="employee.Calendar" />
<h2> Calendar of
<jsp:getProperty name="calendar" property="username" /> </h2>
jsp:getProperty
The <jsp:getProperty> element gets a bean property value using the
property's getter methods and inserts the value into the response. You
must create or locate a bean with <jsp:useBean> before you use
<jsp:getProperty>.
jsp:useBean Example
<html><body>
<form method=‘post’ action=‘usebeanexample.jsp’>
Name:<input type=‘text’ name=‘name’/><br>
Branch:<input type=‘text’ name=‘address’/><br>
RollNo:<input type=‘text’ name=‘rollNo’/><br>
Date of Birth:<input type=‘text’ name=‘dob’/><br>
<input type=‘submit’/><input type=‘reset’/>
</form>
</body></html>
jsp:useBean Example
public class Student{
String name,address,rollNo,dob;
public Student(){}
String getName(){ return name;}
String setName(String name){this.name=name;}
String geAddress(){ return address;}
String setAddress(String address){this.address=address;}
String getRollNo(){ return rollNo;}
String setRollNo(String rollNo){this.rollNo=rollNo;}
String getDOB(){ return dob;}
String setDOB(String dob){this.dob=dob;}
}
jsp:usebean Example
Usebeanexample.jsp
<%@page language=‘java’ %>
<jsp:useBean id=‘stuobj’ class=“Student” scope=‘request’>
<jsp:setProperty name=‘stuobj’ property=‘name’/>
<jsp:setProperty name=‘stuobj’ property=‘address’/>
<jsp:setProperty name=‘stuobj’ property=‘rollNo’
param=‘rollNo’/>
<jsp:setProperty name=‘stuobj’ property=‘DOB’
param=‘dob’/>
</jsp:useBean>
<% out.print(“student name is”+stuobj.getName()); %>