Unit-III (JSP)
Unit-III (JSP)
2
JSP Page
• A JSP page is a page created by the web developer that includes JSP
technology-specific tags, declarations, and possibly scriptlets, in
combination with other static HTML or XML tags.
• A JSP page has the extension .jsp; this signals to the web server that the
JSP engine will process elements on this page.
• Pages built using JSP technology are typically implemented using a
translation phase that is performed once, the first time the page is called.
The page is compiled into a Java Servlet class and remains in server
memory, so subsequent calls to the page have very fast response times.
• Put .jsp pages into a WAR file (see Web ARchive)
• Deploy (upload) the WAR file as a Web Application to your Sun Java
System Application Server Platform.
3
Overview
• JavaServer Pages (JSP) lets you separate the dynamic
part of your pages from the static HTML.
HTML tags and text
<% some JSP code here %>
HTML tags and text
<I>
<%= request.getParameter("title") %>
</I>
You normally give your file a .jsp extension, and
typically install it in any place you could place a normal
Web page
4
Client and Server with JSP
5
Translation Time
• A JSP application is usually a collection of JSP
files, HTML files, graphics and other resources.
• A JSP page is compiled when your user loads it
into a Web browser
1. When the user loads the page for the first time, the files that make up the
application are all translated together, without any dynamic data, into one
Java source file (a .java file)
2. The .java file is compiled to a .class file. In most implementations, the .java
file is a Java servlet that complies with the Java Servlet API.
6
Simple JSP Page
<HTML>
<H1> First JSP Page </H1>
<BODY>
<% out.println(“Welcome to JSP world”); %>
</BODY>
</HTML>
7
How JSP Works?
User Request – JSP File Requested
Server
File
Create Source from JSP Changed
8
JSP Elements
• Declarations <%! code %>
C
o
<jsp:declaration>
p </jsp:declaration >
y
r
i
• Expressions g
h
<%= expression %>
t
@
2 <jsp:expression>
0
0
0
</jsp:expression>
J
o
• Scriplets r
d
<% code %>
a
n
A <jsp:scriplet>
n
a </jsp:scriplet >
s
t
9
a
HTML Comment
• Generates a comment that is sent to the client.
– Syntax
– Example:
<!-- This page was loaded on
<%= (new java.util.Date()).toLocaleString() %>
-->
10
Declaration
• Declares a variable or method valid in the scripting language used in the JSP
page.
– Syntax
<%! declaration; [ declaration; ]+
... %>
– Examples
<%! String destin; %>
<%! Public String getDestination()
{return destin;}%>
<%! Circle a = new Circle(2.0); %>
– You can declare any number of variables or methods within one declaration
element, as long as you end each declaration with a semicolon.
– The declaration must be valid in the Java programming language.
11
Declaration Example
<HTML>
<HEAD><TITLE>JSP Declarations</TITLE></HEAD>
<BODY><H1>JSP Declarations</H1>
12
Predefined Variable – Implicit Objects
• request – Object of HttpServletRequest (request parameters, HTTP headers, cookies
13
Expression
• Contains an expression valid in the scripting language used in the JSP page.
– Syntax
14
Expression Example
<HTML>
<HEAD>
<TITLE>JSP Expressions</TITLE>
</HEAD>
<BODY>
<H2>JSP Expressions</H2>
<UL>
<LI>Current time: <%= new java.util.Date() %>
<LI>Your hostname: <%= request.getRemoteHost() %>
<LI>Your session ID: <%= session.getId() %>
</UL>
</BODY>
</HTML>
15
Scriptlet
• Contains a code fragment valid in the page scripting
language.
– Syntax
<% code fragment %>
<%
String var1 = request.getParameter("name");
out.println(var1);
%>
16
Scriplet Example
<HTML>
<HEAD><TITLE>Weather</TITLE></HEAD>
<BODY>
<H2>Today's weather</H2>
</BODY>
</HTML>
17
JSP Lifecycle
Servlet from JSP
Request
Response
jspService()
18
JSP Page Directive
• Directives are messages to the JSP container and do not produce output
into the current output stream
– Syntax:
<%@ directive attribute=“value” %>
<%@ directive attribute1=“value1”
attribute1 =“value2” … %>
19
Page Directive
• Defines attributes that apply to an entire JSP page.
<%@ page
[ import="{package.class | package.*}, ..." ]
[ errorPage="relativeURL" ]
[ contentType="mimeType
[ charset=characterSet]”
[ isErrorPage="true|false" ]
[ buffer="none|8kb|sizekb" ]
[ autoFlush="true|false" ]
[ isThreadSafe="true|false" ]
[ info="text" ]
[ language="java" ]
[ extends="package.class" ]
[ session="true|false" ]
%>
20
Include Directive
• Includes a static file in a JSP file, parsing the file's JSP elements.
– Syntax
<%@ include file="relativeURL" %>
The <%@ include %> directive inserts a file of text or code in a JSP file at
translation time, when the JSP file is compiled.
<%@ include %> process is static. A static include means that the text of the
included file is added to the JSP file.
The included file can be:
1. JSP file,
2. HTML file,
3. text file.
21
Taglib Directive
The <%@ taglib %> directive declares that the JSP file uses custom tags, names the
tag library that defines them, and specifies their tag prefix.
Note:
(1) The custom tags are extensions to the JSP language.
(2) Some examples of tasks that can be performed by custom tags include
operating on implicit objects,
processing forms,
accessing databases and
other enterprise services such as email and directories, and implementing flow
control.
(3) Custom tags increase productivity because they can be reused in more than one
application.
22
Taglib Directive
• Defines a tag library and prefix for the custom tags
used in the JSP page.
– Syntax
<%@ taglib uri="URIToTagLibrary" prefix="tagPrefix" %>
Example:
• Core Tags
• Formatting tags
• SQL tags
• XML tags
• JSTL Functions
23
SQL tags
• The JSTL SQL tag library provides tags for
interacting with relational databases (RDBMSs)
such as Oracle, mySQL, or Microsoft SQL Server.
• Following is the syntax to include JSTL SQL library
in your JSP:
26
• <body>
• <sql:setDataSource var="snapshot"
driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/TEST"
user="root"
password="pass123"/>
• <sql:update dataSource="${snapshot}" var="result">
INSERT INTO Employees VALUES (104, 2, 'Neha', ‘Sunil');
• </sql:update>
• </body>
• </html>
27
JSP Action Tags
• jsp:forward
forwards the request and response to another resource.
• jsp:include
includes another resource.
• jsp:useBean
creates or locates bean object.
• jsp:setProperty
sets the value of property in bean object.
• jsp:getProperty
prints the value of property of the bean.
28
<jsp:forward>
• Forwards a client request to an HTML file, JSP file, or
servlet for processing.
– Syntax
<jsp:forward page="{relativeURL | <%= expression %>}" />
29
jsp:forward
• index.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" />
</body>
</html>
• printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
30
<jsp:useBean>
• Locates or instantiates a bean with a specific name
and scope.
<jsp:useBean
id="beanInstanceName"
scope="page|request|session|application"
{ class="package.class" |
type="package.class" |
class="package.class" type="package.class" |
beanName="{package.class | <%= expression %>}“
}
{ /> |
> other elements
</jsp:useBean>
}
31
Attributes and Usage
• id="beanInstanceName"
A variable that identifies the bean in the scope you specify. The name is
case sensitive and must conform to the naming conventions of the scripting
language used in the JSP page
scope="page|request|session|application“
page One can use the bean within the JSP page with the <jsp:useBean>
element or any of the page's static include files, until the page sends a
response back to the client or forwards a request to another resource
request One can use the bean from any JSP page processing the same
request, until a JSP page sends a response to the client or forwards the
request to another resource. One can use the request object to access the
bean, for example, request.getAttribute(beanInstanceName).
32
Attributes and Usage
session One can use the bean from any JSP page in the same session as the
JSP page that created the bean. The bean exists across the entire session,
and any page that participates in the session can use it. The page in which
you create the bean must have a page directive with session="true".
application One can use the bean from any JSP page in the same
application as the JSP page that created the bean. The bean exists across an
entire JSP application, and any page in the application can use the
33
Different Scope
Most visible
{ property="*" |
property="propertyName" [ param="parameterName" ] |
property="propertyName" value="{string | <%= expression
%>}"
}
/>
– Examples
<jsp:setProperty name="mybean" property="*" />
<jsp:setProperty name="mybean" property="username" />
<jsp:setProperty name="mybean" property="username" value="Steve" />
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>.
35
<jsp:getProperty>
• Gets the value of a bean property so that you can
display it in a result page.
– Syntax
<jsp:getProperty name="beanInstanceName“
property="propertyName" />
– Example:
<jsp:useBean id="calendar" scope="page" class="employee.Calendar" />
<h2>
Calendar of <jsp:getProperty name="calendar" property="username" />
</h2>
36
JavaBean
• A JavaBean is a specially constructed Java class written in
the Java and coded according to the JavaBeans API
specifications.
• Following are the unique characteristics that distinguish a
JavaBean from other Java classes:
- It provides a default, no-argument constructor.
- It should be serializable and implement
the Serializable interface.
- It may have a number of properties which can be read or
written.
- It may have a number of "getter" and "setter" methods for
the properties.
37
JavaBean properties
• JavaBean properties are accessed through two
methods in the JavaBean's implementation class:
getPropertyName()
For example, if property name is firstName, your
method name would be getFirstName() to read
that property. This method is called accessor.
setPropertyName()
For example, if property name is firstName, your
method name would be setFirstName() to write
that property. This method is called mutator.
38
JavaBean Example
package com.tutorialspoint;
public class StudentsBean implements
java.io.Serializable {
private String firstName = null;
private String lastName = null;
private int age = 0;
public StudentsBean() { }
public String getFirstName(){ return firstName; }
public String getLastName(){ return lastName; }
public int getAge(){ return age; }
39
JavaBean Example
public void setFirstName(String firstName){
this.firstName = firstName; }
public void setLastName(String lastName){
this.lastName = lastName; }
public void setAge(Integer age){ this.age = age; }
}
40
Accessing Javabeans properties
Syntax:
41
Accessing Javabeans properties
<html>
<head>
<title>get and set properties Example</title>
</head>
<body> <jsp:useBean id="students"
class="com.tutorialspoint.StudentsBean">
<jsp:setProperty name="students"
property="firstName" value="Zara"/>
<jsp:setProperty name="students"
property="lastName" value="Ali"/>
<jsp:setProperty name="students"
property="age" value="10"/>
42
Accessing Javabeans properties
<p>Student First Name:
<jsp:getProperty name="students“
property ="firstName"/>
</p>
<p>Student Last Name:
<jsp:getProperty name="students"
property="lastName"/>
</p>
<p>Student Age: <jsp:getProperty name="students" property="age"/>
</p>
</jsp:useBean>
</body>
</html>
43
Output
Student First Name: Zara
Student Last Name: Ali
Student Age: 10
44
Jsp with Beans
45