Java_Lecture 6 -Java Server Pages
Java_Lecture 6 -Java Server Pages
Lecture 6
Java Server Pages
Coverage
• Introduction
• Scripting elements
• Implicit objects
• Directive elements
• Exception handling
• Action elements
• Expression language
• MVC in JSP
• JSTL
• Custom tags
• Development in JSP
Java Server Pages
INTRODUCTION
What is JSP?
• JSP is the technology used to create web
applications (similar to Servlet technology)
• It is an extension to servlet but provides
additional functionality than servlet (eg:
expression language, jstl (JSP Standard Tag
Library) etc)
• A JSP page has both HTML and JSP tags
JSP page
• Easy to maintain than servlet (due to separate
designing and development)
• Provides additional features such as
Expression Language, Custom Tag etc.
Advantages of JSP over Servlet
• Extension to Servlet
• Easy maintenance
• Fast development
• Less code than Servlet
Extension to Servlet
• Possible to use all features of servlet in
addition to JSP specific features (such as
implicit objects, predefined tags, expression
language and custom tags)
• This make JSP development easy
Easy maintenance
• JSP separates business logic from presentation
logic making managing JSP easy (servlets mix
presentation logic and business logic)
Fast Development
• When a JSP page is modified, it does not
require to be recompiled to be deployed
(When a servlet is modified it needs to be
recompiled)
Less code than servlet
• JSP uses a lot of tags (Eg: action tags, jstl,
custom tags), Expression Language (EL),
implicit objects etc.
• This reduces code
Life cycle of a JSP page
Buffer dynamic
Client
content
JSP Servlet
object
SERVER
Translation
Translator JRE
of JSP page
Compilation of
JSP page
Class
Servlet
Compiler Class file loading
(.java file)
by class
loader
Life cycle of a JSP page
• JSP page is translated into servlet by the JSP
translator
• The JSP translator is a part of webserver that
is responsible to translate the JSP page into
servlet.
• After that Servlet page is compiled by the
compiler and gets converted into the class file.
• Servlet object is created
Phases of JSP
• Translation of JSP Page
• Compilation of JSP Page
• Classloading (class file is loaded by the classloader)
• Instantiation (Object of the Generated Servlet is
created).
• Initialization ( jspInit() method is invoked by the
container).
• Request processing ( _jspService() method is invoked
by the container).
• Destroy ( jspDestroy() method is invoked by the
container).
Directory structure of JSP
• The directory structure of JSP page similar to
servlet.
• JSP page is located outside the WEB-INF folder
or in any directory.
Directory structure of JSP
webapps
(context-
root)
WEB-INF
web.xml
Static resources (eg:
HTML, Images,css
etc) lib
Java Server Pages
<html>
<body>
<H1>
<% out.print(2*5); %>
</H1>
</body>
</html>
Steps to follow
• Create the index.jsp file
• Create a new folder called jsp in the webapps
folder of Tomcat server
• Place index.jsp in this folder
• Start the Tomcat server
• Access the following url using the web
browser by the url
– http://localhost:8080/jsp/jspfile
Output: Example 1
When the directory structure is
required
• There is no need of directory structure if there
are no class files or tld files.
• If a bean class, Servlet or tld file is available
then directory structure is required
• If not put jsp files in a folder directly and
deploy that folder.
The JSP API
• Two packages:
– javax.servlet.jsp
– javax.servlet.jsp.tagext
javax.servlet.jsp package
JspPage JspWriter
Interfaces
Classes
HttpJspPage PageContext
JspFactory
JspEngineInfo
JspException
JspError
The JspPage interface
• All the generated Servlet
servlet classes must
implement the JspPage
extends
interface.
• It extends the Servlet
JSPPage
interface.
extends
HttpJSPPage
Methods of JspPage interface
• public void jspInit():
– It is invoked only once during the life cycle of JSP
(when JSP page is requested initially)
– Same as the init() method of Servlet interface.
– Perform initialization.
• public void jspDestroy():
– It is invoked only once during the life cycle of JSP
(before the JSP page destroys)
– Perform clean up operation.
The HttpJspPage interface
• This interface has one life cycle method of JSP
(_jspService()) and extends the JspPage
interface.
Method of HttpJspPage interface
• public void _jspService():
– Invoked at each request for the JSP page in the
container.
– The underscore _ signifies that the method cannot
be overridden
Java Server Pages
Back
Java Server Pages
SCRIPTING ELEMENTS
JSP Scriptlet tag (Scripting elements)
• Java code can be written inside a JSP page
using Scripting elements or Scriptlet tag.
• Three types
– scriptlet tag
– expression tag
– declaration tag
Java Server Pages
Back
Java Server Pages
IMPLICIT OBJECTS
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.
JSP Implicit Objects
Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
out implicit object
• For writing any data to the buffer, JSP provides
an implicit object named out.
• It is the object of JspWriter.
• Syntax
– PrintWriter out=response.getWriter();
• But in JSP, you don't need to write this code.
Java Server Pages
out.print("Welcome "+request.getParameter("uname"));
String driver=config.getInitParameter("dname");
out.print("driver name is="+driver);
%>
</body>
</html>
Output
Output
web.xml
<servlet>
<servlet-name>anne</servlet-name>
<jsp-file>/Welcome.jsp</jsp-file>
<init-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>anne</servlet-name>
<url-pattern>/Welcome</url-pattern>
</servlet-mapping>
</web-app>
application implicit object
• In JSP, application is an implicit object of type
ServletContext.
• This object can be used to get configuration
information from configuaration file(web.xml).
• This variable information can be used for all
jsp pages
Java Server Pages
</body>
</html>
welcome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=application.getInitParameter("dname");
out.print("driver name is="+driver);
%>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"
version="3.0">
<display-name>welcome</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
web.xml
<servlet>
<servlet-name>anne</servlet-name>
<jsp-file>welcome.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>anne</servlet-name>
<url-pattern>welcome</url-pattern>
</servlet-mapping>
<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
</web-app>
Output
Output
session implicit object
• In JSP, session is an implicit object of type
HttpSession.
• The Java developer can use this object to
set,get or remove attribute or to get session
information.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1"
welcome.jsp
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
%>
<a href="second.jsp">second jsp page</a>
</body>
</html>
second.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
Output
Output
Output
pageContext implicit object
• In JSP, pageContext is an implicit object of type
PageContext class.
• The pageContext object can be used to set, get or
remove attribute from one of the following
scopes:
– page
– request
– session
– application
• In JSP, page scope is the default scope.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=ISO-
8859-1"
welcome.jsp
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
pageContext.setAttribute("user",name,pageContext.SESSION_SCOPE)
;
%>
<a href="second.jsp">second jsp page</a>
</body>
</html>
second.jsp
<%@ page language="java" contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String
name=(String)pageContext.getAttribute("user",pageContext.SESSIO
N_SCOPE);
out.print("Hello "+name);
%>
</body>
</html>
Output
Output
Output
page implicit object
• In JSP, page is an implicit object of type Object
class.
• This object is assigned to the reference of auto
generated servlet class.
• It is written as:
– Object page=this;
• For using this object it must be cast to Servlet
type.
page implicit object
• For example:
– <% (HttpServlet)page.log("message"); %>
• Since, it is of type Object it is less used
because you can use this object directly in jsp.
• For example:
– <% this.log("message"); %>
exception implicit object
• In JSP, exception is an implicit object of type
java.lang.Throwable class.
• This object can be used to print the exception.
• But it can only be used in error pages.It is
better to learn it after page directive.
error.jsp
</body>
</html>
Back
Java Server Pages
DIRECTIVE ELEMENTS
JSP directives
• These are messages that inform the web
container on how to translate a JSP page into
the corresponding servlet.
• Three types:
– page directive
– include directive
– taglib directive
• Syntax of JSP Directive
– <%@ directive attribute="value" %>
JSP page directive
• The page directive defines attributes that
apply to an entire JSP page.
• Syntax of JSP page directive
– <%@ page attribute="value" %>
Attributes of JSP page directive
• import
• contentType
• extends
• info
• buffer
• language
• isELIgnored
• isThreadSafe
• autoFlush
• session
• pageEncoding
• errorPage
• isErrorPage
import
• The import attribute is used to import class,
interface or all the members of a package.
• It is similar to import keyword in java class or
interface.
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>
Output
contentType
• The contentType attribute defines the
MIME(Multipurpose Internet Mail Extension)
type of the HTTP response.
• The default value is "text/html;charset=ISO-
8859-1".
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%@ page contentType="text/html; charset=ISO-8859-1" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
Output
extends
• The extends attribute defines the parent class
that will be inherited by the generated servlet.
• It is rarely used.
info
• This attribute simply sets the information of
the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.
• The web container will create a method
getServletInfo() in the resulting servlet.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Include Directive</h1>
</body>
</html>
Output
JSP Taglib directive
• The JSP taglib directive is used to define a tag
library that defines many tags.
• The TLD (Tag Library Descriptor) file is used to
define the tags.
• These tags are dealt under Custom tags
• Syntax JSP Taglib directive
– <%@ taglib uri="uriofthetaglibrary" prefix="prefix
oftaglibrary" %>
Example of JSP Taglib directive
• A tag named currentDate is used in this
example.
• Specify the taglib directive to use this tag so
that the container may get information on the
tag.
index.jsp
<html>
<body>
<mytag:currentDate/>
</body>
</html>
Back
Java Server Pages
process.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Insert title here</title>
</head>
<body>
<%@ page errorPage="error.jsp" %>
<%
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
//out.print("division of numbers is: "+c);
%>
</body>
</html>
error.jsp
<%@ page language="java" contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<error-page>
<exception-
type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>
</web-app>
web.xml file to handle the exception
for a specific error code
• If the specific error code is known, specify the
error-code element instead of exception-type
as given below:
<web-app>
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>
</web-app>
Example of exception handling in jsp
by specifying the error-page element
in web.xml file
• There are 4 files:
– web.xml file for specifying the error-page element
– index.jsp for input values
– process.jsp for dividing the two numbers and
displaying the result
– error.jsp for displaying the exception
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No1:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
process.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
</body>
</html>
error.jsp
<%@ page language="java" contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>Sorry an exception occurred!</h3>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
web.xml
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"
version="3.0">
<display-name>Exception</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page> Back
</web-app>
Java Server Pages
ACTION ELEMENTS
JSP Action Tags (Action Elements)
• There are variety of JSP action tags /
elements.
• Each tag is perform a specific tasks.
• The action tags are used to control the flow
between JSP pages and Java Beans.
JSP Action Tags (Action Elements)
• Action tags used in JSP are:
– jsp:forward
– jsp:include
– jsp:useBean
– jsp:setProperty
– jsp:getProperty
– jsp:plugin
– jsp:param
– jsp:fallback
• The jsp:useBean, jsp:setProperty and jsp:getProperty
tags are used for bean development.
jsp:forward action tag
• The jsp:forward action tag is used to forward
the request to another resource (jsp, html or
another resource).
– Syntax of jsp:forward action tag without
parameter
• <jsp:forward page="relativeURL | <%= expression %>" /
>
– Syntax of jsp:forward action tag with parameter
<jsp:forward page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parametervalue | <%=expression%>" />
</jsp:forward>
Example of jsp:forward action tag
without parameter
• Simply forward the request from index.jsp to
the printdate.jsp
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
<title>Index Page</title>
</head>
<body>
<h2>this is index page</h2>
</body>
</html>
printdate.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>Print Date</title>
</head>
<body>
<% out.print("Today
is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
Example of jsp:forward action tag
with parameter
• Forwarding the request to the printdate.jsp
file with parameter and printdate.jsp file
prints the parameter value with date and
time.
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Index Page</title>
</head>
<body>
<h2>this is index page</h2>
</body>
</html>
printdate.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>Print Date</title>
</head>
<body>
<% out.print("Today
is:"+java.util.Calendar.getInstance().getTime()); %> <br>
<%= request.getParameter("name") %>
</body>
</html>
jsp:include action tag
• The jsp:include action tag is used to include
the content of another resource (jsp, html or
servlet).
• The jsp include action tag is good for dynamic
pages as the resources are available at request
time
• Advantage of jsp:include action tag
– code reusability
jsp:include action tag
• Syntax of jsp:include action tag without
parameter
– <jsp:include page="relativeURL | <%= expression
%>" />
• Syntax of jsp:include action tag with
parameter
<jsp:include page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parametervalue | <%=expression%>" />
</jsp:include>
Example of jsp:include action tag
without parameter
• index.jsp file includes the content of the
printdate.jsp file.
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>Index Page</title>
</head>
<body>
<h2>this is index page</h2>
</body>
</html>
printdate.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>Print Date</title>
</head>
<body>
<% out.print("Today
is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
Output
Java Bean
• A Java Bean is a java class
• It has the following features
– It has a no-arg constructor.
– It is Serializable.
– It has setter and getter methods to set and get
values of properties
Why use Java Bean?
• It is a reusable software component.
– A bean encapsulates many objects into one object
(promoting reusability)
• Provides the easy maintenance.
Simple example of java bean class
• Two classes
– Employee class – simple java bean class
– Test class
• How to access the java bean class?
– To access the java bean class, we should use getter
and setter methods
• Note: There are two ways to provide values to
the object, one way is by constructor and
second is by setter method.
Employee.java
public class Employee {
private int id;
private String name;
public Employee(){}
}
Test.java
public class Test {
System.out.println(e.getName());
}
}
jsp:useBean action tag
• Used to locate or instantiate a bean class.
– If bean object is created then it does not create
the bean
– If object of bean is not created, then it creates the
bean object
jsp:useBean action tag
• Syntax of jsp:useBean action tag
<jsp:useBean id= "instanceName" scope= "page | request | session | ap
plication"
class= "packageName.className" type= "packageName.className"
beanName="packageName.className | <%= expression >" >
</jsp:useBean>
Attributes and Usage of jsp:useBean
action tag
• id: identify the bean for the given scope
• scope: scope of the bean - page, request, session or
application.
– page: the bean is used within a page. The default scope is
page.
– request: the bean can be used from any JSP page that
processes the same request (has wider scope than page).
– session: the bean can be used from any JSP page in the
same session whether processes the same request or not
(has wider scope than request).
– application: the bean can be used from any JSP page in the
same application (has wider scope than session).
Attributes and Usage of jsp:useBean
action tag
• class: creates an object of the bean class with no-
arg or no constructor and must not be abstract.
• type: provides the bean a data type if the bean
already exists in the scope. It is mainly used with
class or beanName attribute. If you use it without
class or beanName, no bean is instantiated.
• beanName: instantiation of the the bean using
the java.beans.Beans.instantiate() method.
Simple example of jsp:useBean action
tag
• Create a new package myPackage in the
project
• Create the class Calculator.java under this
package
• Compile this class and place the
Calculator.class in the WebContent/WEB-
INF/classes/myPackage folder of the project
Calculator.java
package myPackage;
<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);
%>
</body>
</html>
Output
jsp:setProperty and jsp:getProperty
action tags
• For the development of web applications with
Java Bean, the setProperty and getProperty
action tags are used.
• The bean class is mostly used in web
development because it is a reusable software
component that represents data.
• The jsp:setProperty action tag uses the setter
method of a bean in setting the property
value or values in a bean.
jsp:setProperty and jsp:getProperty
action tags
• Syntax of jsp:setProperty action tag
<jsp:setProperty name="instanceOfBean" property= "*" |
property="propertyName" param="parameterName" |
property="propertyName" value="{ string | <%= expression %>}"
/>
</body>
</html>
welcome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="obj" class="myPackage.User" />
<jsp:setProperty name="obj" property="*" />
}
Output
Output
Reusing Bean in Multiple Jsp Pages
• Prints the data of bean object in two JSP
pages.
• Files in the project
– index.jsp
– User.java
– process.jsp
– second.jsp
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="process.jsp" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
Email:<input type="text" name="email"><br>
<input type="submit" value="register">
</form>
</body>
</html>
User.java
package myPackage;
}
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1"
process.jsp
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="u" class="myPackage.User"
scope="session"></jsp:useBean>
<jsp:setProperty property="*" name="u"/>
Record:<br>
<jsp:getProperty property="name" name="u"/><br>
<jsp:getProperty property="password" name="u"/><br>
<jsp:getProperty property="email" name="u" /><br>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
process.jsp
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="u" class="myPackage.User" scope="session"></jsp:useBean>
<%
String name="amali";
String password = "abc123";
String email = "amali@gg.lk";
%>
<jsp:setProperty property="name" name="u" value="<%=name %>"/>
<jsp:setProperty property="password" name="u" value="<%=password %>"/>
<jsp:setProperty property="email" name="u" value="<%=email %>"/>
Record:<br>
<jsp:getProperty property="name" name="u" /><br>
<jsp:getProperty property="password" name="u"/><br>
<jsp:getProperty property="email" name="u" /><br>
Back
Java Server Pages
<a href="process.jsp">visit</a>
</body>
</html>
process.jsp
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Value is ${sessionScope.user}
</body>
</html>
Output
Output
Precedence of Operators in EL
[] .
()
-(unary) not ! empty
* / div % mod
+ - (binary)
< <= > >= lt le gt ge
== != eq ne
&& and
|| or
?:
Reserve words in EL
lt le gt ge
eq ne true false
and or not instanceof
div mod empty null
Back
Java Server Pages
MVC IN JSP
MVC in JSP
• MVC stands for Model View and Controller.
• It is a design pattern that separates the business
logic, presentation logic and data.
– View represents the presentation i.e. UI(User
Interface).
– Model represents the state of the application i.e. data.
It can also have business logic.
– Controller acts as an interface between View and
Model. Controller intercepts all the incoming
requests.
Advantage of MVC Architecture
• Navigation Control is centralized
• Easy to maintain the large application
Java Server Pages
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
String name=request.getParameter("name");
String password=request.getParameter("password");
ControllerServlet.java
LoginBean bean=new LoginBean();
bean.setName(name);
bean.setPassword(password);
request.setAttribute("bean",bean);
boolean status=bean.validate();
if(status){
RequestDispatcher rd=request.getRequestDispatcher("login-
success.jsp");
rd.forward(request, response);
}
else{
RequestDispatcher rd=request.getRequestDispatcher("login-
error.jsp");
rd.forward(request, response);
}
}
ControllerServlet.java
@Override
protected void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
web.xml
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"
version="3.0">
<display-name>mvc</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>myPackage.ControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/ControllerServlet</url-pattern>
</servlet-mapping>
</web-app>
Output
Output
Back
Java Server Pages
EXAMPLE OF C:CATCH
Example of c:catch
<h2>Data is:</h2>
<c:out value="${data}"></c:out>
</body>
</html>
Output
c:forEach
• It repeats the nested body content for fixed
number of times or over collection.
Java Server Pages
EXAMPLE OF C:FOREACH
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:forEach var="number" begin="5" end="10">
<c:out value="${number}"></c:out>
</c:forEach>
</body>
</html>
Output
c:if
• It tests the condition.
Java Server Pages
EXAMPLE OF C:IF
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>Insert title here</title>
</head>
<body>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="number" value="${200}"> </c:set>
<c:if test="${number<500}">
<c:out value="number is less than 500"></c:out>
</c:if>
</body>
</html>
Output
c:redirect
• It redirects the request to the given url.
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>Insert title here</title>
</head>
<body>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:redirect url="http://www.univotec.ac.lk"></c:redirect>
</body>
</html>
Output
Back
Java Server Pages
Extends
Tag
IterationTag
BodyTag TagSupport
BodyTagSupport
JSP Custom Tag API
• JspTag interface
– The root interface for all the interfaces and classes
used in custom tag.
– It is a marker interface.
• Tag interface
– Sub interface of JspTag interface
– Has methods to perform action at the start and
end of the tag
Fields of Tag interface
Field Name Description
public static int EVAL_BODY_INCLUDE Evaluates the body content.
public static int EVAL_PAGE Evaluates the JSP page content after the
custom tag.
public static int SKIP_BODY Skips the body content of the tag.
public static int SKIP_PAGE Skips the JSP page content after the custom
tag.
Methods of Tag interface
Method Name Description
public void Sets the given PageContext object.
setPageContext(PageContext pc)
public void setParent(Tag t) Sets the parent of the tag handler.
public Tag getParent() Returns the parent tag handler object.
public int doStartTag()throws Invoked by the JSP page implementation
JspException object. The JSP programmer should override
this method and define the business logic to be
performed at the start of the tag.
public int doEndTag()throws Invoked by the JSP page implementation
JspException object. The JSP programmer should override
this method and define the business logic to be
performed at the end of the tag.
public void release() Invoked by the JSP page implementation object
to release the state.
IterationTag interface
• The sub interface of the Tag interface.
• It provides an additional method to reevaluate the body.
• Field of IterationTag interface
– There is only one field
• public static int EVAL_BODY_AGAIN
– reevaluates the body content.
• Method of Tag interface
– There is only one method
• public int doAfterBody()throws JspException
– Invoked by the JSP page implementation object after the evaluation of the
body.
– If this method returns EVAL_BODY_INCLUDE, body content will be re-
evaluated, if it returns SKIP_BODY, no more body content will be evaluated.
TagSupport class
• Implements the IterationTag interface.
• It acts as the base class for new Tag Handlers.
• Provides some additional methods as well.
Java Server Pages
Tag Handler
TLD File
class
Define tag
JSP File Business logic
name and Tag
Use tag to be
Handler class
performed in
tag
Create the Tag handler class
• Create the Tag Handler, inheriting the
TagSupport class and overriding its method
doStartTag().
• To write data for the jsp, use the JspWriter
class
• The PageContext class provides getOut()
method that returns the instance of JspWriter
class.
MyTagHandler.java
• TagSupport class provides instance of
pageContext bydefault.
• Create the package myPkg under Resources
src
• Create the class MyTagHandler.java
• Select project right click Properties Java
Build Path Add Library Server Runtime
Apache Tom Cat 7 Finish
• Create the mytags.tld file inside the WEB-INF
folder
MyTagHandler.java
package myPkg;
import java.util.Calendar;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
<!DOCTYPE taglib
mytags.tld
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>http://tomcat.apache.org/example-taglib</uri>
<tag>
<name>today</name>
<tag-class>myPkg.MyTagHandler</tag-class>
</tag>
</taglib>
Create the JSP file
• Specifying the path of tld file directly in the
tag of JSP file
• Recommended to use the uri name instead of
full path of tld file.
• It uses taglib directive to use the tags defined
in the tld file.
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>Insert title here</title>
</head>
<body>
<%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>http://tomcat.apache.org/example-taglib</uri>
<description>A simple tab library for the examples</description>
<tag>
<name>cube</name>
<tag-class>myPkg.CubeNumber</tag-class>
<attribute>
<name>number</name>
<required>true</required>
</attribute>
</tag>
</taglib>
package myPkg; CubeNumber.java
import javax.servlet.jsp.JspException; Import the relevant
import javax.servlet.jsp.JspWriter; package for
import javax.servlet.jsp.tagext.TagSupport; javax.servlet
public class CubeNumber extends TagSupport{ Click your project
private int number; Right click
Properties Java
public void setNumber(int number) { Build Path Libraries
this.number = number; Add library
} ServerTime Apache
Tomcat v7.0
public int doStartTag() throws JspException {
JspWriter out=pageContext.getOut();
try{
out.print(number*number*number);
}catch(Exception e){e.printStackTrace();}
return SKIP_BODY;
}
}
Java Server Pages
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>http://tomcat.apache.org/example-taglib</uri>
<description>A simple tab library for the examples</description>
<tag>
<name>power</name>
<tag-class>myPkg.PowerNumber</tag-class>
<attribute>
<name>number</name>
<required>true</required>
</attribute>
<attribute>
<name>power</name>
<required>true</required>
</attribute>
</tag>
</taglib>
PowerNumber.java
package myPkg;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
return EVAL_PAGE;
}
}
Output
Java Server Pages
<uri>exampleuri</uri>
<tag>
<name>loop</name>
<tag-class>myPkg.Loop</tag-class>
<attribute>
<name>start</name>
<required>true</required>
</attribute>
<attribute>
<name>end</name>
<required>true</required>
</attribute>
</tag>
</taglib>
Loop.java
package myPkg;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
@Override
public int doStartTag() throws JspException {
return EVAL_BODY_INCLUDE;
}
@Override
public int doAfterBody() throws JspException {
if(start<end){
start++;
return EVAL_BODY_AGAIN;
}else{
return SKIP_BODY;
}
}
<?xml version="1.0" encoding="UTF-8"?>
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"
version="3.0">
<display-name>CustomerIterate</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<jsp-config>
<taglib>
<taglib-uri>exampleuri</taglib-uri>
<taglib-location>/WEB-INF/mytags.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>
Java Server Pages
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>mytags</uri>
<description>A simple tab library for the examples</description>
<tag>
<name>today</name>
<tag-class>myPkg.PrintDate</tag-class>
</tag>
</taglib>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<display-name>CustomUri</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<jsp-config>
<taglib>
<taglib-uri>mytags</taglib-uri>
<taglib-location>/WEB-INF/mytags.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>
PrintDate.java
package myPkg;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
return SKIP_BODY;
}
}
Output
Java Server Pages
DEVELOPMENT IN JSP
Development in JSP
• We are going to develop a small web based
applications with JSP for the following
– Registration form
– Login form
– Uploading file
– Downloading file
Creating the database and the table
• Create a database userdetails in MS SQL
server with the table ‘users’
• The users table has the following
– Name – varchar
– Email – varchar
– Password – varchar
Java Server Pages
<%
int status=RegisterDao.register(obj);
if(status>0)
out.print("You are successfully registered");
%>
</body>
</html>
Provider.java
package myPkg;
import java.sql.*;
import static myPkg.Provider.*;
status=ps.executeUpdate();
}catch(Exception e){}
return status;
}
}
Output
Output
SQL Server Output
Java Server Pages
int i;
while ((i=fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
%>
</body>
</html>
Output