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

Java_Lecture 6 -Java Server Pages

The document provides an overview of Java Server Pages (JSP), detailing its advantages over servlets, including easier maintenance, faster development, and reduced code complexity. It covers the lifecycle of a JSP page, scripting elements, and examples of using JSP scriptlet, expression, and declaration tags. Additionally, it explains the directory structure for JSP and the implicit objects available in JSP pages.

Uploaded by

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

Java_Lecture 6 -Java Server Pages

The document provides an overview of Java Server Pages (JSP), detailing its advantages over servlets, including easier maintenance, faster development, and reduced code complexity. It covers the lifecycle of a JSP page, scripting elements, and examples of using JSP scriptlet, expression, and declaration tags. Additionally, it explains the directory structure for JSP and the implicit objects available in JSP pages.

Uploaded by

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

Enterprise Java

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

JSP classes class files

web.xml
Static resources (eg:
HTML, Images,css
etc) lib
Java Server Pages

EXAMPLE 1: CREATING A SIMPLE


JSP PAGE
index.jsp

<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

CREATING JSP IN ECLIPSE IDE WITH


TOMCAT SERVER
Step 1: Create the dynamic web
project
• To create a dynamic web project click on File
Menu -> New -> dynamic web project -> write
your project name e.g. first -> Finish.
Step 1: Create the dynamic web
project
Step 1: Create the dynamic web
project
Step 1: Create the dynamic web
project
Step 1: Create the dynamic web
project
Step 1: Create the dynamic web
project
Step 2: Create the JSP file in eclipse
IDE
• For creating a jsp file explore the project by
clicking the + icon -> right click on
WebContent -> New -> jsp -> write your jsp
file name e.g. index -> next -> Finish
Step 2: Create the JSP file in eclipse
IDE
Step 2: Create the JSP file in eclipse
IDE
Step 2: Create the JSP file in eclipse
IDE
Step 2: Create the JSP file in eclipse
IDE
Step 2: Create the JSP file in eclipse
IDE
• Now JSP file is created, let's write some code.
Step 3: Start the server and deploy
the project
• Configure the tomcat server first.
• For configuring the tomcat server in eclipse
IDE, click on servers tab at the bottom side of
the IDE -> right click on blank area -> New ->
Servers -> choose tomcat then its version ->
next -> click on Browse button -> select the
apache tomcat root folder previous to bin ->
next -> addAll -> Finish.
Step 3: Start the server and deploy
the project
Step 3: Start the server and deploy
the project
Step 3: Start the server and deploy
the project
Step 3: Start the server and deploy
the project
Step 3: Start the server and deploy
the project
Step 3: Start the server and deploy
the project
Step 3: Start the server and deploy
the project
• Now tomcat7 server has been configured in
eclipse IDE.
Step 3: Start the server and deploy
the project
• Now start the tomcat server and deploy
project
• For starting the server and deploying the
project in one step Right click on your project -
> Run As -> Run on Server -> choose tomcat
server -> next -> addAll -> finish
Step 3: Start the server and deploy
the project
Step 3: Start the server and deploy
the project
Step 3: Start the server and deploy
the project
Step 3: Start the server and deploy
the project
Step 3: Start the server and deploy
the project
• JSP is successfully running now

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

JSP SCRIPTLET TAG


JSP Scriptlet tag
• A Scriptlet tag is used to execute java source
code in JSP.
• Syntax:
– <% java source code %>
Java Server Pages

EXAMPLE: DISPLAYING A WELCOME


MESSAGE USING JSP SCRIPLET TAG
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>
<h2>Hello JSP</h2>
<% out.print("welcome to jsp"); %>
</body>
</html>
Java Server Pages

EXAMPLE: JSP SCRIPTLET TAG THAT


PRINTS THE USER NAME
Example: JSP scriptlet tag that prints
the user name
• Create a new project welcome
• The project has two files
– index.html
– welcome.jsp
• Run the project on Tomcat server
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>
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>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</body>
</html>
Output
Output
Java Server Pages

JSP EXPRESSION TAG


JSP expression tag
• The code inside the expression tag is written
to the output stream of the response.
• There is no need to for out.print() to write
data.
• It is used to print the values of variable or
method.
• Syntax
– <%= statement %>
Java Server Pages

EXAMPLE: JSP EXPRESSION TAG


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>
<h2>Hello JSP</h2>
<%= "welcome to jsp hello" %>
</body>
</html>
Output
Java Server Pages

EXAMPLE: JSP EXPRESSION TAG FOR


PRINTING CURRENT 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>Insert title here</title>
</head>
<body>
<h2>Hello JSP</h2>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
Java Server Pages

EXAMPLE: JSP EXPRESSION TAG THAT


PRINTS THE USER NAME
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"><br/>
<input type="submit" value="go">
</form>
</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>
<%= "Welcome "+request.getParameter("uname") %>
</body>
</html>
Java Server Pages

JSP DECLARATION TAG


JSP declaration tag
• This is used to declare fields and methods.
• The code written inside the JSP declaration tag
is placed outside the service() method of auto
generated servlet.
• Syntax
– <%! field or method declaration %>
Difference between the jsp scriptlet
tag and jsp declaration tag
Jsp Scriptlet Tag Jsp Declaration Tag
The jsp scriptlet tag can only declare The jsp declaration tag can declare variables
variables not methods. as well as methods.
The declaration of scriptlet tag is placed The declaration of jsp declaration tag is
inside the _jspService() method. placed outside the _jspService() method.
Java Server Pages

EXAMPLE: JSP DECLARATION TAG


THAT DECLARES FIELD
JSP declaration tag that declares field
• A field is declared and the value of the
declared field is printed using the JSP
expression tag.
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>
<%! int data=50; %> <%= "Value of the variable is:"+data %>
</body>
</html>
Output
Java Server Pages

EXAMPLE: JSP DECLARATION TAG


THAT DECLARES METHOD
JSP declaration tag that declares
method
• This method returns the cube of given number
and calls the method from the JSP expression
tag (can also use JSP scriptlet tag to call
declared method)
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>
<%!
int cube(int n){
return n*n*n;
}
%>

<%= "Cube of 3 is:"+cube(3) %>


</body>
</html>
Output

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

EXAMPLE: OUT IMPLICIT OBJECT


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>
<% out.print("Today
is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
Output
request implicit object
• In JSP, request is an implicit object of type
HttpServletRequest.
Java Server Pages

EXAMPLE: REQUEST IMPLICIT


OBJECT
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>
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>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</body>
</html>
Output
Output
response implicit object
• In JSP, response is an implicit object of type
HttpServletResponse.
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>
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>
<%
response.sendRedirect("http://www.google.com");
%>
</body>
</html>
Output
Output
config implicit object
• In JSP, config is an implicit object of type
ServletConfig.
• This object can be used to get configuration
information for a particular JSP page.
• This variable information can be used for one
jsp page only.
Java Server Pages

EXAMPLE: CONFIG IMPLICIT OBJECT


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>
<%

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

EXAMPLE: APPLICATION IMPLICIT


OBJECT
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>
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

<%@ page isErrorPage="true" %>


<html>
<body>

Sorry following exception occured:<%= exception %>

</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.

public String getServletInfo() {


return "composed by Gayathri Gunawardena";
}
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 info="composed by Gayathri Gunawardena" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
buffer
• The buffer attribute sets the buffer size in
kilobytes to handle output generated by the
JSP page.
• The default size of the buffer is 8Kb.
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 buffer="16kb" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
language
• The language attribute specifies the scripting
language used in the JSP page.
• The default value is "java".
isELIgnored
• The Expression Language (EL) in JSP will be
ignored by the isELIgnored attribute.
• By default this value is false i.e. Expression
Language is enabled by default.
– <%@ page isELIgnored="true" %>//Now EL will be
ignored
isThreadSafe
• Both Servlet and JSP are multithreaded.
• This behaviour of JSP page can be controlled
by using isThreadSafe attribute of page
directive.
• The default value of isThreadSafe is true.
• If this is made false, the web container will
serialize the multiple requests (wait until the
JSP finishes responding to a request before
passing another request)
isThreadSafe
• If the value of isThreadSafe attribute is:
– <%@ page isThreadSafe="false" %>
• The web container generate the servlet as:
public class SimplePage_jsp extends HttpJspBase
implements SingleThreadModel{
.......
}
errorPage
• If an exception occurs in the current page the
errorPage attribute, redirect to the error page.
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 errorPage="myErrorPage.jsp" %>
<%= 100/0 %>
</body>
</html>
myErrorPage.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>
<h1>ERROR!!!!</h1>
</body>
</html>
isErrorPage
• The isErrorPage attribute is used to declare
that the current page is the error page.
• Note: The exception object can only be used
in the error page.
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 isErrorPage="true" %>

Sorry an exception occurred!<br/>


The exception is: <%= exception %>
</body>
</html>
Output
Java Server Pages

JSP INCLUDE DIRECTIVE


JSP Include Directive
• The include directive is used to include the
contents of any resource (eg: jsp file, html file
or text file).
• The include directive has the original content
of the included resource at the time of page
translation
JSP Include Directive
• Advantage of Include directive
– Code Reusability
• Syntax of include directive
– <%@ include file="resourceName" %>
Example of include directive
• Include the content of the header.html file in
this example.
• Create a header.html file to use with this
example.
• Note: The include directive includes the
original content, therefore the actual page size
grows at runtime.
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>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
header.html

<!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>

<%@ taglib uri="http://www.google.lk" prefix="mytag" %>

<mytag:currentDate/>

</body>
</html>

Back
Java Server Pages

EXCEPTION HANDLING IN JSP


Exception Handling in JSP
• An exception is an object thrown at runtime.
• An exception can occur at any time in the web
application.
• Handling exceptions is done for safer use of
web application
• Exception Handling is the process of handling
the runtime errors.
Exception Handling in JSP
• In JSP, two ways are available for exception
handling:
– By errorPage and isErrorPage attributes of page
directive
– By <error-page> element in web.xml file
Example of exception handling in JSP
by the elements of page directive
• Define and create a page to handle the
exceptions (eg: error.jsp page).
• The pages in which where exception occur, define
the errorPage attribute of page directive (eg:
process.jsp page).
• There are 3 files:
– index.jsp for input values
– process.jsp for dividing the two numbers and
displaying the result
– error.jsp for handling 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>
<%@ 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>

<h3>Sorry an exception occurred!</h3>


</body>
</html>
Output
Output
Output
Output
Example of exception handling in jsp
by specifying the error-page element
in web.xml file
• With this approach there is no need to specify
the errorPage attribute in each JSP page.
• It is a single entry in the web.xml file to deal
with the exception.
• In this case, specify exception-type or error-
code with the location element.
web.xml file to handle any exception
• If there is a need to handle all the exception,
then specify the java.lang.Exception in the
exception-type element.
• This approach is better to deal with any
exception.
<web-app>

<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>

<jsp:forward page="printdate.jsp" />

</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>

<jsp:forward page="printdate.jsp" >


<jsp:param name="name" value="google.lk" />
</jsp:forward>

</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>

<jsp:include page="printdate.jsp" />

<h2>end section of 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(){}

public void setId(int id){this.id=id;}

public int getId(){return id;}

public void setName(String name){this.name=name;}

public String getName(){return name;}

}
Test.java
public class Test {

public static void main(String[] args) {


Employee e=new Employee();//object is created

e.setName("Gayathri");//setting value to the object

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;

public class Calculator {


public int cube(int n){return n*n*n;}
}
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>
<jsp:useBean id="obj" class="myPackage.Calculator"/>

<%
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 %>}"
/>

• Example of jsp:setProperty action tag all the


values of incoming request in the bean have
to be set
<jsp:setProperty name="bean" property="*" />
jsp:setProperty and jsp:getProperty
action tags
• Example of jsp:setProperty action tag to set
value of the incoming specific property
<jsp:setProperty name="bean" property="username" />

• Example of jsp:setProperty action tag to set a


specific value in the property
<jsp:setProperty name="bean" property="username" value="Kumara" />
jsp:getProperty action tag
• The jsp:getProperty action tag returns the
value of the property.
• Syntax of jsp:getProperty action tag
<jsp:getProperty name="instanceOfBean" property="propertyName" />

• Simple example of jsp:getProperty action tag


<jsp:getProperty name="obj" property="name" />
Example of bean development in JSP
• In this example there are 3 pages:
– index.html for input of values
– welcome.jsp file that sets the incoming values to
the bean object and prints the one value
– User.java bean class that have setter and getter
methods
• Compile the User.java and place inside the
folder \WebContent\WEB-
INF\classes\myPackage of the project
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="welcome.jsp">
Enter Name:<input type="text" name="name"/>
<input type="submit" value="go" />
</form>

</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="*" />

Welcome, <jsp:getProperty name="obj" property="name" />


</body>
</html>
User.java
package myPackage;

public class User{


private String name;

public void setName(String name){


this.name=name;
}
public String getName(){
return name;
}

}
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;

public class User{


private String name;

public void setName(String name){


this.name=name;
}
public String getName(){
return name;
}

}
<%@ 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>

<a href="second.jsp">Visit 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>
<jsp:useBean id="u" class="myPackage.User"
scope="session"></jsp:useBean>
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>
Output
Output
Output
Using variable value in setProperty
tag
• In order to set some value from the database,
that is to be set in the bean object, the
expression tag can be used.
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>
<%@ 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>

<a href="second.jsp">Visit 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>
<jsp:useBean id="u" class="myPackage.User"
scope="session"></jsp:useBean>
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>
Output
Output
Output
Displaying an Applet in JSP
• There are two files in this project
– index.jsp
– Time.java – This should be created in under the
default package in Java
• Project  Build project
• The Time.class is created in the build/classes folder
• Copy the file
• Create a new folder called Test under WebContent
folder of project
• Place Time.class file inside this folder
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>
<jsp:plugin type="applet" code="Time.class" codebase="test"
width = "200" height = "200">
<jsp:fallback>
<p>Unable to load applet</p>
</jsp:fallback>
</jsp:plugin>
</body>
</html>
Time.java
import java.applet.*;
import java.awt.*;
import java.util.*;

public class Time extends Applet{


public void paint(Graphics g){
Calendar cal = new GregorianCalendar();
String hour = String.valueOf(cal.get(Calendar.HOUR));
String minute = String.valueOf(cal.get(Calendar.MINUTE));
String second = String.valueOf(cal.get(Calendar.SECOND));
g.drawString(hour + ":" + minute + ":" + second, 20, 30);
}
}
Displaying an Applet in JSP
• The applet is blocked for viewing in Eclipse
• You can view the Applet in browser
• Change the security level to medium in Java
control panel
Output
Java control panel
Output in browser

Back
Java Server Pages

EXPRESSION LANGUAGE (EL) IN JSP


Expression Language (EL) in JSP
• The Expression Language (EL) makes access to
data stored in the Java Bean component (and
other objects like request, session, application
etc.) simple
• EL has many implicit objects, operators and
reserve words.
• It is a newly added feature in JSP technology
version 2.0.
Expression Language (EL) in JSP
• Syntax for Expression Language (EL)
– ${ expression }
Implicit Objects in Expression
Language (EL)
Implicit Objects Usage
pageScope it maps the given attribute name with the value set in the page
scope
requestScope it maps the given attribute name with the value set in the request
scope
sessionScope it maps the given attribute name with the value set in the session
scope
applicationScope it maps the given attribute name with the value set in the application
scope
param it maps the request parameter to the single value
paramValues it maps the request parameter to an array of values
header it maps the request header name to the single value
headerValues it maps the request header name to an array of values
cookie it maps the given cookie name to the cookie value
initParam it maps the initialization parameter
pageContext it provides access to many objects request, session etc.
Simple example of Expression
Language that prints the name of the
user
• Create two files
– index.jsp - The index.jsp file gets input from the
user and sends the request to the process.jsp
– process.jsp – The process.jsp which in turn prints
the name of the user using EL.
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">
Enter name:<input type="text" name="name"/><br/><br/>
<input type="submit" value="go"/>
</form>
</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>
Welcome, ${param.name}
</body>
</html>
Output
Output
Example of Expression Language that
prints the value set in the session
scope
• In this example, the data stored in the session
scope is printed using EL.
• For this purpose, sessionScope object is used
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>
<h3>Welcome to index page</h3>
<%
session.setAttribute("user","Gayathri");
%>

<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

EXAMPLE ON MVC IN JSP


Example on MVC in JSP
• There are five pages in this example
• index.jsp - page that gets input from the user.
• ControllerServlet.java - servlet that acts as a
controller.
• login-success.jsp and login-error.jsp files - acts
as view components.
• web.xml file for mapping the servlet.
How to add the javax.servlet package
to a project?
• Right click your project folder, select Properties at
the bottom of the context menu.
• Select "Java Build Path"
• Click Libraries" tab
• Click "Add Library..." button on right (about
halfway down)
• Select "Server Runtime" click "Next"
• Select your Tomcat version from the list
• Click Finish
Adding javax.servlet package in
Eclipse
Adding javax.servlet package in
Eclipse
Adding javax.servlet package in
Eclipse
Adding javax.servlet package in
Eclipse
Adding javax.servlet package in
Eclipse
Adding javax.servlet package in
Eclipse
Adding javax.servlet package in
Eclipse
• Create the package ‘myPackage’
• Add the java files to this package
• Build project
– To obtain the classes for the java programs
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>
<form action="ControllerServlet" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
<input type="submit" value="login">
</form>
</body>
</html>
login-success.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>Login Success</title>
</head>
<body>
<%@page import="myPackage.LoginBean"%>

<p>You are successfully logged in!</p>


<%
LoginBean bean=(LoginBean)request.getAttribute("bean");
out.print("Welcome, "+bean.getName());
%>
</body>
</html>
login-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>
<p>Sorry! username or password error</p>
<%@ include file="index.jsp" %>
</body>
</html>
package myPackage;

public class LoginBean {


LoginBean.java
private String name,password;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getPassword() {


return password;
}

public void setPassword(String password) {


this.password = password;
}

public boolean validate(){


if(password.equals("admin")){
return true;
}
else{
return false;
}
}
}
ControllerServlet.java
package myPackage;

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;

public class ControllerServlet extends HttpServlet {

protected void doPost(HttpServletRequest request,


HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();

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

JSTL (JSP STANDARD TAG LIBRARY)


JSTL
• The JSP Standard Tag Library (JSTL) represents
a set of tags to simplify the JSP development.
• Advantage of JSTL
– Fast Development
• JSTL provides many tags that simplifies the JSP.
– Code Reusability
• We can use the JSTL tags in various pages.
– No need to use scriptlet tag
• It avoids the use of scriptlet tag.
JSTL
• For creating JSTL application, load jstl.jar file.
– Download jstl-1.2.jar from
http://download.java.net/maven/1/jstl/jars/
– Copy jstl-1.2.jar to WEB-INF/lib directory
• JSTL mainly provides 5 types of tags
JSTL tags
Tag Name Description
core tags The JSTL core tag provide variable support, URL management, flow
control etc. The url for the core tag
is http://java.sun.com/jsp/jstl/core . The prefix of core tag is c.
sql tags The JSTL sql tags provide SQL support. The url for the sql tags is
http://java.sun.com/jsp/jstl/sql and prefix is sql.
xml tags The xml sql tags provide flow control, transformation etc. The url
for the xml tags is http://java.sun.com/jsp/jstl/xml and prefix is x.
internationalization The internationalization tags provide support for message
tags formatting, number and date formatting etc. The url for the
internationalization tags ishttp://java.sun.com/jsp/jstl/fmt and
prefix is fmt.
functions tags The functions tags provide support for string manipulation and
string length. The url for the functions tags
is http://java.sun.com/jsp/jstl/functions and prefix is fn.
JSTL Core Tags
• The JSTL core tags mainly provides 4 types of
tags:
– miscellaneous tags: catch and out.
– url management tags: import, redirect and url.
– variable support tags: remove and set.
– flow control tags: forEach, forTokens, if and choose.
• Syntax for defining core tags
– <%@ taglib uri="http://java.sun.com/jsp/jstl/core" pre
fix="c" %>
c:catch
• It is an alternative approach of global
exception handling of JSP.
• It handles the exception and doesn't
propagate the exception to error page.
• The exception object thrown at runtime is
stored in a variable named var.
Java Server Pages

EXAMPLE OF C:CATCH
Example of c:catch

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


<c:catch>
int a=10/0;
</c:catch>
c:out
• It is just like JSP expression tag but it is used
for expression.
• It renders data to the page.
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" method="post">
FirstName:<input type="text" name="fname"/><br/>
LastName:<input type="text" name="lname"/><br/>
<input type="submit" value="submit"/>
</form>
</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>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
First Name:<c:out value="${param.fname}"></c:out><br/>
Last Name:<c:out value="${param.lname}"></c:out>
</body>
</html>
Output
Output
c:import
• It is just like jsp include but it can include the
content of any resource either within server or
outside the server.
Java Server Pages

EXAMPLE OF C:IMPORT TO DISPLAY


THE SOURCE CODE
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" %>
<h1>ABC.com</h1>
<hr/>
<c:import var="data" url="http://www.univotec.ac.lk"></c:import>

<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

CUSTOM TAGS IN JSP


Custom Tags
• These are user-defined tags.
• They eliminate the scriptlet tag
• Separates the business logic from the JSP page
and the same business logic can be used many
times with the use of custom tag.
Advantages of Custom Tags
• Eliminates the need of srciptlet tag
– Srciptlet tag is considered a bad programming
approach in JSP
• Separates business logic from JSP
– Easy to maintain
• Reusability
– The same business logic can be reused by custom
tags
Syntax
• Two ways of using Custom tag
<prefix:tagname attr1=value1....attrn=valuen />

<prefix:tagname attr1=value1....attrn=valuen >


body
</prefix:tagname>
JSP Custom Tag API
• Package - javax.servlet.jsp.tagext
• The root interface in the Custom Tag hierarchy
is JspTag
JSP Custom Tag API
Implement JspTag

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

EXAMPLE – USING CUSTOM TAG


Example of JSP Custom Tag
• Creating a custom tag that prints the current date
and time
• Perform action at the start of tag
• Steps
– Create the Tag handler class - perform action at the
start or at the end of the tag
– Create the Tag Library Descriptor (TLD) file and define
tags
– Create the JSP file that uses the Custom tag defined in
the TLD file
Flow of custom tag in JSP

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;

public class MyTagHandler extends TagSupport{


public int doStartTag() throws JspException {
JspWriter out=pageContext.getOut();
try{
out.print(Calendar.getInstance().getTime());
}catch(Exception e){System.out.println(e);}
return SKIP_BODY;
}
}
MyTagHandler.java
• Build the project
• Copy the class file to WEB-INF  classes 
myPkg
Create the TLD file
• Tag Library Descriptor (TLD) file contains
information of tag and Tag Hander classes.
• It must be contained inside the WEB-INF
directory.
<?xml version="1.0" encoding="ISO-8859-1" ?>

<!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" %>

Current Date and Time is: <m:today/>


</body>
</html>
Output
Attributes in JSP custom tags
• Many attributes can be defined for a Custom
Tag
• Two tasks needs to be performed before
defining an attribute
– Define the property (with attribute name and
setter method) in the TagHandler class
– Define the attribute element tag element (in TLD
file)
Java Server Pages

EXAMPLE: USING ATTRIBUTES WITH


JSP CUSTOM TAG
Example: using attributes with JSP
Custom Tag
• Use the cube tag which return the cube of any
given number
• Files in project
– index.jsp
– CubeNumber.java place in src/myPkg
– mytags.tld – Place in WEB-INF folder
– Build the project
• Copy the classes folder under build to WEB-
INF
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" %>
Cube of 4 is: <m:cube number="4"></m:cube>
</body>
</html>
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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>
<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

ITERATION USING JSP CUSTOM TAG


Iteration using JSP Custom Tag
• Iterate the body content of any tag using the
doAfterBody() method of IterationTag
interface
• Use the TagSupport class which implements
the IterationTag interface.
• For iterating the body content, need to use
the EVAL_BODY_AGAIN constant in the
doAfterBody() method
Java Server Pages

EXAMPLE OF ITERATION USING JSP


CUSTOM TAG
Example of Iteration using JSP Custom
Tag
• Use the attribute in the custom tag, which
returns the power of any given number
• Files in the project
– index.jsp
– PowerNumber.java
– mytags.tld
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" %>

3 ^ 5 = <m:power number="3" power="5"> body


</m:power>
</body>
</html>
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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>
<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;

public class PowerNumber extends TagSupport{


private int number;
private int power;
private static int counter;
private static int result=1;

public void setPower(int power) {


this.power = power;
}

public void setNumber(int number) {


this.number = number;
}
public int doStartTag() throws JspException {
return EVAL_BODY_INCLUDE;
}

public int doAfterBody() {


counter++;
result *= number;
if (counter==power)
return SKIP_BODY;
else
return EVAL_BODY_AGAIN;
}

public int doEndTag() throws JspException {


JspWriter out=pageContext.getOut();
try{
out.print(result);
}catch(Exception e){e.printStackTrace();}

return EVAL_PAGE;
}

}
Output
Java Server Pages

LOOPING USING ITERATION TAG


Looping using Iteration Tag
• Creating a tag for loop
• Create a loop tag that iterates the body
content of this tag.
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 prefix="m" uri="exampleuri" %>
<m:loop end="5" start="1">
<p>Example of custom tag uri</p>
</m:loop>
</body>
</html>
mytags.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
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>abc</short-name>

<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;

public class Loop extends TagSupport{


private int start=0;
private int end=0;

public void setStart(int start) {


this.start = start;
}
public void setEnd(int end) {
this.end = end;
}

@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

CUSTOM URI IN JSP CUSTOM TAG


Custom URI in JSP Custom Tag
• Custom URI, tell the web container about the
tld file.
• Define the taglib element in the web.xml.
• The web container gets the information about
the tld file from the web.xml file for the
specified URI.
Java Server Pages

EXAMPLE TO USE CUSTOM URI IN


JSP CUSTOM TAG
Example to use custom URI in JSP
Custom Tag
• The project has the following four files
– index.jsp
– mytags.tld
– web.xml
– PrintData.java
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="mytags" prefix="m" %>

Today is: <m:today></m:today>


</body>
</html>
mytags.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
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>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;

public class PrintDate extends TagSupport{

public int doStartTag() throws JspException {


JspWriter out=pageContext.getOut();
try{
out.print(java.util.Calendar.getInstance().getTime());
}catch(Exception e){e.printStackTrace();}

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

CREATING THE REGISTRATION


FORM IN JSP
Creating the registration form in JSP
• We have the following files
– index.jsp – for obtaining input values from the
user
– User.java – A bean class that has properties
(name, email and password) and the setter and
getter methods
– process.jsp - processes the request and calls the
methods
Creating the registration form in JSP
• We have the following files contd…
• Provider.java - An interface containing constants
DRIVER_CLASS, CONNECTION_URL, USERNAME and
PASSWORD
• ConnectionProvider.java - Class returns an object of
Connection (It uses the Singleton and factory method
design pattern)
• RegisterDao.java - A DAO class to get access to the
database
Configuring the JDBC driver
• Compile all classes and interfaces in the
project
– Project  Clean
• Download Microsoft JDBC Driver 4.0 for SQL
Server from http://www.microsoft.com/en-
us/download/confirmation.aspx?id=11774
• Run and extract the files to C:\Program
files\Microsoft JDBC Driver 4.0 for SQL Server
folder
Configuring the JDBC driver
• Copy sqljdbc4.jar file to the WEB-INF/lib folder
• Right click on project Properties  Java
Build Path  Libraries  Add JARs  Select
Project/WebContent/Web-INF/lib
• Go to SQL Server Configuration Manager and
ensure that TCP/IP is enabled
– Click on TCP/IP  Set Listen all
– Go to  IP address  set TCP Port for IP address
as 1433
<%@ page language="java" contentType="text/html; charset=ISO-8859-
1"
index.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>
<form action="process.jsp">
<p>
Name:<input type="text" name="uname" value="Name"
onclick="this.value=''"/><br/>
Email: <input type="text" name="uemail" value="EmailID"
onclick="this.value=''"/><br/>
Password: <input type="password" name="upass" value="Password"
onclick="this.value=''"/><br/></p>
<input type="submit" value="register"/>
</form>
</body>
</html>
package myPkg;

public class User {


User.java
private String uname,upass,uemail;

public String getUname() {


return uname;
}

public void setUname(String uname) {


this.uname = uname;
}

public String getUpass() {


return upass;
}

public void setUpass(String upass) {


this.upass = upass;
}

public String getUemail() {


return uemail;
}

public void setUemail(String uemail) {


this.uemail = uemail;
}
}
<%@ 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>
<%@page import="myPkg.RegisterDao"%>
<jsp:useBean id="obj" class="myPkg.User"/>

<jsp:setProperty property="*" name="obj"/>

<%
int status=RegisterDao.register(obj);
if(status>0)
out.print("You are successfully registered");

%>
</body>
</html>
Provider.java
package myPkg;

public interface Provider {


String DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";
String CONNECTION_URL="jdbc:sqlserver://localhost:1433";
String USERNAME="sa";
String PASSWORD="admin123";
}
ConnectionProvider.java
package myPkg;

import java.sql.*;
import static myPkg.Provider.*;

public class ConnectionProvider {

private static Connection con=null;


static{
try{
Class.forName(DRIVER);
con=DriverManager.getConnection(CONNECTION_URL,USERNAME,PASSWORD);
}catch(Exception e){}
}

public static Connection getCon(){


return con;
}
}
package myPkg; RegisterDao.Java
import java.sql.*;

public class RegisterDao {

public static int register(User u){


int status=0;
try{
Connection con=ConnectionProvider.getCon();
PreparedStatement ps=con.prepareStatement("insert into
userdetails.dbo.users values(?,?,?)");
ps.setString(1,u.getUname());
ps.setString(2,u.getUemail());
ps.setString(3,u.getUpass());

status=ps.executeUpdate();
}catch(Exception e){}

return status;
}
}
Output
Output
SQL Server Output
Java Server Pages

UPLOADING FILE TO THE SERVER


USING JSP
Uploading file to the server using JSP
• Many ways of uploading a file to the server
• One way is to use the MultipartRequest class
based on Apache Common FileUpload API,
servlet and JSP
• The project consists of the following files
– index.jsp
– upload.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>Insert title here</title>
</head>
<body>
<form ENCTYPE="multipart/form-data" ACTION="upload.jsp"
METHOD=POST>
<br>
<br>
<br>
<center>
<table border="0" bgcolor=#ccFDDEE>
<tr>
<center>
<td colspan="2" align="center"><B>UPLOAD THE FILE</B>
<center>
</td>
</tr>
<tr>
<td colspan="2" align="center"></td>
</tr>
<tr>
<td><b>Choose the file To Upload:</b></td>
<td><INPUT NAME="file" TYPE="file"></td>
</tr>
<tr>
<td colspan="2" align="center"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"
value="Send File"></td>
</tr>
<table>
</center>
</form>
</body>
</html>
upload.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.io.*"%>
<%
String saveFile = "";
String contentType = request.getContentType();
if ((contentType != null) &&
(contentType.indexOf("multipart/form-data") >= 0)) {
DataInputStream in = new
DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead,
formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
saveFile = file.substring(file.indexOf("filename=\"") +
10);
saveFile = saveFile.substring(0,
saveFile.indexOf("\n"));
saveFile =
saveFile.substring(saveFile.lastIndexOf("\\") + 1,
saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,
contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0,
pos)).getBytes()).length;
int endPos = ((file.substring(0,
boundaryLocation)).getBytes()).length;
saveFile = "G:/new/" + saveFile;
File ff = new File(saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos -
startPos));
fileOut.flush();
fileOut.close();
%><Br>
<table border="2">
<tr>
<td><b>You have successfully upload the file by the
name of:</b>
<%
out.println(saveFile);
}
%>
</td>
</tr>
</table>
</body>
</html>
Output
Output
Java Server Pages

DOWNLOADING FILE FROM SERVER


TO CLIENT USING 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>Insert title here</title>
</head>
<body>
<a href="download.jsp">download the jsp file</a>
</body>
</html>
download.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 filename = "Enterprise Java Beans.pptx";
String filepath = "g:\\new\\";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment; filename=\""
+ filename + "\"");
download.jsp
java.io.FileInputStream fileInputStream = new
java.io.FileInputStream(filepath + filename);

int i;
while ((i=fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
%>
</body>
</html>
Output

You might also like