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

Chapter-10(JSPJSTL)

Java Server Pages (JSP) is a server-side technology used for creating dynamic web applications by embedding Java code within HTML. The document outlines the JSP lifecycle, key components, and differences between JSP and Servlets, as well as various JSP scripting elements like comments, scriptlets, expressions, and declarations. Additionally, it explains JSP directives and their attributes, which guide how JSP files are processed and integrated with Java code.

Uploaded by

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

Chapter-10(JSPJSTL)

Java Server Pages (JSP) is a server-side technology used for creating dynamic web applications by embedding Java code within HTML. The document outlines the JSP lifecycle, key components, and differences between JSP and Servlets, as well as various JSP scripting elements like comments, scriptlets, expressions, and declarations. Additionally, it explains JSP directives and their attributes, which guide how JSP files are processed and integrated with Java code.

Uploaded by

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

Java Server Pages : About JSP&JSTL

©https://blogs.ashrithgn.com/
What is JSP Page?

• Java Server Pages (JSP) is a server side technology that does all the processing
at server.
• JSP have access to the entire family of Java APIs, including the JDBC API to
access enterprise databases.
• JSP is used for creating dynamic java web applications.
• Dynamic webpages are usually a mix of static and dynamic content.
• Static content can have text-based formats such as HTML, XML, etc .
• Dynamic content is generated by JSP tags using java code inside HTML .

Faculty of Computer Science


Static and Dynamic Contents

• Static contents
• Typically static HTML page
• Same display for everyone
• Dynamic contents
• Contents is dynamically generated based on conditions
• Conditions could be
• User identity
• Time of the day
• User entered values through forms and selections
• Examples
• E-Trade webpage customized just for you, my Yahoo

Faculty of Computer Science


A Simple JSP Page

<html>
<head>
<title>Sample JSP</title>
</head>
<% int sampleVar=0; %>
<body>
Count is:
<% out.println(++sampleVar); %>
</body>
</html>

Faculty of Computer Science


JSP Vs Servlet

• JSP • Servlet
1. JSP program is a HTML 1. Servlet is a Java program
code which supports java which supports HTML
statements too. To be more tags too.
precise, JSP embed java in 2. Generally used for
html using JSP tags. developing business
2. Used for developing layer(the complex
presentation layer of an computational code) of an
enterprise application enterprise application.
3. Frequently used for 3. Servlets are created and
designing websites and maintained by
used by web developers. Java developers.
Faculty of Computer Science
A Java Servlet : Looks like a regular Java program

public class SampleJSP_jsp extends HttpServlet{


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Sample JSP</title></head>");
int sampleVar=0;
out.println("<body>");
out.println("Count is: " + (++sampleVar) );
out.println("</body></html>");
}
Faculty of Computer Science
}
JSP Architecture

https://javabeat.net/jsp-architecture-lifecycle/
Faculty of Computer Science
JSP Page Lifecycle

Translation – JSP Compilation – ClassLoading –


File Servlet File Servlet Class
Handel multiple request and
sends response Called Once
Request Instantiation – one
Initialisation –
Processing – or more instances
jspInit()
jspService() of Servlet Class
Called Once

Destroy –
jspDestroy()

Faculty of Computer Science


JSP Page Lifecycle Phases

• A JSP page goes through the below phases:


1.Translation – A JSP file (demo.jsp) is translated into java servlet file (demo_jsp.java).
2.Compilation – The generated java servlet file (demo_jsp.java) is compiled into a java servlet
class (demo_jsp.class).
3.ClassLoading – The servlet file (demo_jsp.java) is loaded into java servlet class
(demo_jsp.class).
4.Instantiation – One or more instances of this class in response to requests and other events
are managed.
5.Initialisation – jspInit() method is called immediately after the instance was created and only
once during JSP life cycle.
6.Request Processing – jspService() is called for every request of this JSP during its life cycle.
In this phase a response is generated for the user based on the request made by them.
7.Destroy – jspDestroy() method is called in this phase to unload the JSP from the memory. This
is also known as cleanup step.
• JSP life cycle methods : jspInit(), jspService() and jspDestroy()
Faculty of Computer Science
Key Components of JSP

• There are four key components to JSPs—


• Scripting Elements

• Directives

• Actions

• Tag libraries

Faculty of Computer Science


JSP Scripting Elements

• JSP scripting elements are one of the most vital elements of a JSP code

• JSP scripting elements include the following:


• Comments <%-- and --%>

• Scriptlets: <% java code %>

• Expressions: <%= Expressions %>

• Declarations: <%! Declarations %>

Faculty of Computer Science


JSP Comment

• Comment tag allows to show just only information.

• Syntax of Comment tag:

<% -- Comment --%>

Faculty of Computer Science


JSP Comment Example

<html>
<body>

<%--
Using JSP language, create a system that calculates Body Mass
Index (BMI) of users who entered their weight(lb) and height(in).
Current formula: BMI = 703*weight(lb)/height(in)^2

--%>
<form name="form" method="get" action="CommentBMI.jsp">
<pre>
Enter Weight: <input type="text" name="Weight"> lb <br>
Enter Height: <input type="text" name="Height"> in <br>
<input type="submit" value="Find BMI"> <br>
</pre> </form>
</body> Faculty of Computer Science
</html>
JSP Scriptlet

• Scriptlet tag allows to write Java code into JSP file.

• JSP container moves statements in _jspservice() method while generating servlet

from jsp.

• A Scriptlet contains java code that is executed every time JSP is invoked.

• Syntax of Scriptlet tag:

<% java code %>

Faculty of Computer Science


JSP Scriptlet Example
<%-- Using Scriplet tag --%>
<%
String wt=request.getParameter("Weight");
String ht=request.getParameter("Height");
if(wt != null && ht !=null){
int weight=Integer.parseInt(wt);
int height=Integer.parseInt(ht);
int w=weight*703;
int h=height*height;
int bmi = w/h;
out.println("BMI of weight "+weight+" and height "+height+" is: "+bmi);
}
%> Faculty of Computer Science
JSP Expression

• Expression tag is used to insert the result of a java expression directly into the
output
• It allows create expressions like arithmetic and logical.
• It can use instead of out.print() method but must not use a semicolon to end an
expression
• Syntax:
<%= expression %>

Faculty of Computer Science


JSP Expression Example
<%
String wt=request.getParameter("Weight");
String ht=request.getParameter("Height");
if(wt != null && ht !=null){
int weight=Integer.parseInt(wt);
int height=Integer.parseInt(ht);
int w=weight*703; int h=height*height;
%>
<%-- Using Expression tag --%>
<%=
"BMI of weight "+ weight +" and height "+ height +" is: "+ (w/h)
%>
Faculty of Computer Science
<%} %>
JSP Declaration

• Declaration tag allows to initialize variables or define procedures for use later in
the JSP

• Code placed in this must end in a semicolon(;).

• It does not generate output, and is used with JSP expressions or scriptlets.

• Syntax

<%! declaration statements %>

Faculty of Computer Science


JSP Declaration Example

<%-- Using Declaration tag --%>


<%!
String wt=null, ht=null;
int weight=0, height=0;
%>
<%-- Using Scriplet tag --%>
<%
wt =request.getParameter("Weight"); <%-- Using Expression tag --%>
<%=
ht =request.getParameter("Height"); "BMI of weight "+weight+" and
if( wt != null && ht !=null){ height "+height+" is: "+w/h
weight = Integer.parseInt(wt); %>
<%
height = Integer.parseInt(ht); }
Faculty of Computer Science
int w = weight * 703; int h = height * height; %>
Example JSP Application using Scripting Elements

• Calculate Factorial Number using with JSP Form

Faculty of Computer Science


web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name> Testing </display-name>
<welcome-file-list>
<welcome-file>FactorialFormJSP.jsp</welcome-file>
</welcome-file-list>
</web-app>

Faculty of Computer Science


FactorialFormJSP.jsp
<html>
<head>
<title>Factorial JSP Form </title>
</head>
<body>
<%! Declaration Tag
int factorial(int n) {
if (n == 1) {
return n;
}
else {
return n * factorial(n - 1);
}
} Faculty of Computer Science
FactorialFormJSP.jsp
<%
String givenInput = request.getParameter("number");
if (givenInput == null) {
%>
<%--
Comment Tag
Display JSP Form
--%>
<h3> Type your number</h3>
<form action="FactorialFormJSP.jsp" method="get"> Scriptlet Tag
<input type="text" name="number"> <br>
<input type="submit"name="submit" value=“Calculate">
</form>
<%
Faculty of Computer Science
} %>
FactorialFormJSP.jsp
<%
else {
int num =Integer.parseInt(givenInput);
if(num<0){
%>
Sorry! Your number is invalid.
<%
}
Scriptlet Tag
else if (num==0){
%>
0! = 1
<%
} Faculty of Computer Science
FactorialFormJSP.jsp

<%
else{
for(int i=1; i<=num; i++){
Scriptlet Tag
%>
<br>
<%=
i+"! = "+ factorial(i)
%>
Expression Tag
<%
}
}
%>
Faculty of Computer Science
FactorialFormJSP.jsp

<br> <a href="FactorialFormJSP.jsp"> Back </a>


<%
}
%> Scriptlet Tag

</body>
</html>

Faculty of Computer Science


Lets make exercise!

Write a program to convert Celsius from Fahrenheit or Fahrenheit from Celsius


based on user’s input using JSP web application.

Faculty of Computer Science


What is JSP Directives?

• JSP directives provide messages or directions to the container on how to


translating JSP to servlet code

• Directives can contain several attributes that are separated by a comma

• The syntax of Directives looks like:

<%@ directive {attribute=value}* %>

Faculty of Computer Science


Three Types of JSP Directives

page Define page-dependent attributes


Directive By convention, page directives are coded at the
top of the JSP page.

include Includes a file during the translation phase.


Directive Place include directive where the included
content want to be appeared

Declares a custom tag library and make


taglib available in the current JSP
Directive
By convention, page directives are coded at
the top of the JSP page

Faculty of Computer Science


Faculty of Computer Science
Basic Syntax for
Directives

page
directive
<%@ page attribute=“value” %>

include
directive
<%@ include file=“relative URL” %>

taglib
directive
<%@ taglib uri=“uri" prefix=“value" %>
Attributes used by page directive

No Attribute Description
1 language The scripting language used in the JSP. Currently, the only valid
(java) value is java.

2 extends Specifies the class from which the translated JSP will be inherited.
This attribute must be a fully qualified class name.

3 import Specifies a comma-separated list of fully qualified type names


and/or packages that will be imported and used in the current JSP.

default import java.lang.*


javax.servlet.*
packages
javax.servlet.jsp.*
javax.servlet.http.* Faculty of Computer Science
Attributes used by page directive Con’t

No Attribute Description
4 session Specifies whether the page participates in a session.
(true) When the page is part of a session, implicit object session is
available for use in the page.
Otherwise, using session in the scripting code results in a
translation-time error.
5 buffer Specify the size of output buffer to store servlet output before
(8kB) directed to the response object.
Set value of "none" to immediately directed servlet output to the
response object.
6 autoFlush Specifies whether to automatically flush buffered output when the
(true) buffer is full.

Faculty of Computer Science


Attributes used by page directive Con’t

No Attribute Description
7 isThreadSafe Specifies whether the page can process multiple request at the
(true) same time.
8 errorPage Specifies the page to sent exception if any exceptions in the
current page are not caught.

9 isErrorPage Specifies if the current page is an error page that will be invoked
(false) in response to an error on another page.
Only the error page can use implicit object exception which
references the occurred exception.
10 contentType Specifies the MIME type of the data in the response to the client.
(text/html;
charset=ISO-
8859-1)
Faculty of Computer Science
Attributes used by page directive Con’t

No Attribute Description
11 info Simply sets the information of the JSP page which is
retrieved later by using getServletInfo() method of Servlet
interface.
12 isELIgnored Determines if Expression Language (EL) is ignored and
(false) treated as static text.
13 isScriptingEnabled Determines if the scripting elements are allowed for use.
(true) If the attribute's value is set to false, a translation-time error
will be raised if the JSP uses any scriptlets, JSP expressions
(non-EL), or JSP declarations

Faculty of Computer Science


Page Directives Usage Examples

• The generated servlet must extend package1.HttpJspBase class

• <%@ page
extends=“package1.HttpJspBase” %>
• java.util.Date class and java.sql package are imported
• <%@ page import="java.util.Date, java.sql.*” %>
• JSP page participates in HTTP sessions
• <%@ page session=“true" %>

Faculty of Computer Science


Page Directives Usage Examples Con’t

• Buffered output should be flushed automatically when buffer size


reachs 16kB
• <%@ page buffer=“16kb” autoFlash=“true” %>
• Current JSP can execute multiple request at a time
• <%@ page isThreadSafe=“true" %>
• solve.jsp page will handles errors occurred in current JSP
• <%@ page errorPage=“solve.jsp" %>
• Current JSP can be used as the error page for another JSP
• <%@ page isErrorPage=“true" %>

Faculty of Computer Science


Page Directives Usage Examples Con’t

• Return Microsoft Word document as response


• <%@ page contentType=“application/msword" %>
• Description of the JSP
• <%@ page info=“Student registration form" %>
• Evaluate Expression Language in current JSP
• <%@ page isELIgonred=“false" %>
• Allow scripting elements for use
• <%@ page isScriptingEnabled=“true" %>

Faculty of Computer Science


Include Directive

• It is used to insert the content, either static or dynamic, contained from another file to
current JSP during the translation phase

• The included content will replace the include directive statement and get translated.

• The file attribute’s value should be the relative URL of the resource from the current
JSP page

• Basic Syntax and Example

• <%@ include file="filename" %>

• <%@ include file="banner.jsp" %>

Faculty of Computer Science


Taglib Directive

• The taglib directive declares that your JSP page uses a set of custom tags.

• When you use a custom tag, it is typically of the form <prefix:tagname> and the
prefix is the same as the prefix you specify in the taglib directive

• Basic syntax
• <%@ taglib uri=“uri" prefix=“value" %>

• Example: Using custom tag, defined with uri /my-tags, with a prefix of mtag; your
tag would be <mtag:tagName>
• <%@ taglib uri = “/my-tags" prefix = “mtag" %>
Faculty of Computer Science
Practice Application Design

main.jsp
header.jsp
h1 and green
color

create date
object and
print

footer.jsp
h3 and blue
color
Faculty of Computer Science
Practice Application: To do List

1. Create a Tomcat project with name


“JSPDirectives”
2. Create header.jsp and footer.jsp at specified
location with mentioned content
3. Create main.jsp by getting a Date object and
printint current date/time. Then includes
header.jsp and footer.jsp
4. Set main.jsp as welcome file by web.xml
5. Deploy the project

Faculty of Computer Science


JavaBean Class

• A JavaBean class is a Java class.


• It provides a default no-argument constructor.
• It should be serializable to be transformed into bye stream as needed.
• It may have a number of properties which can be read or written.
• It should provide methods to set and get the values of the properties, known
as setter and getter methods.
• Getter method names should be getPropertyName() and setter methods name
should be setPropertyName()
• JavaBean can be accessed from JSP by JSP action tags

Faculty of Computer Science


What is JSP Action Tags?

• Predefined JSP tags that encapsulate functionality including:


• Creating a JavaBean instance and accessing its properties
• Forwarding execution to another HTML page, JSP page, or servlet
• Including an external resource in the JSP page
• Syntax for the Action element: Two forms-

Without Parameter:
< jsp:action_name attribute=“value”/>

With Parameter:
< jsp:action_name attribute=“value”>
..... Parameter(s) .....
<jsp:acation_name/>
Faculty of Computer Science
Action tags to access JavaBean

JSP Action Tag Description


The useBean action declares a JavaBean for use in a JSP.
< jsp:useBean> Once declared, the bean becomes a scripting variable that
can be accessed by both scripting elements and other custom
tags used in the JSP.
Set the value of property in the specified JavaBean instance.
<jsp:setProperty> This action automatic match request parameters to bean
properties of the same name.
Gets the value of property of the specified JavaBean
<jsp:getProperty> instance and converts the result to a string for output in the
response.

Faculty of Computer Science


useBean Action Attributes

Attribute Description
id The case sensitive name used to manipulate the Java bean with actions
<jsp:setProperty> and <jsp:getProperty>.

scope The scope in which the Java bean is accessible—page, request, session or
application. The default scope is page.
class The fully qualified class name. Java bean of this class is to be created.

type The type of the reference to hold JavaBean.


This can be the same type as the class attribute, a superclass of that type
or an interface implemented by that type.
The default value is the same as for attribute class.

Faculty of Computer Science


setProperty Action Attributes

Attribute Description
name The name of bean instance whose property’s value is to be set.
(id of jsp:useBean)
property Name of the property that is being set
This attribute is particularly useful for setting bean properties with specified
value value that can’t be set using request parameter. This attribute is optional.

param This attribute is useful for setting bean properties with value of request
parameter whose name is not same with property’s name.
If value and param attributes are omitted, there must be a request
parameter whose name matches with bean property name.

Faculty of Computer Science


getProperty Action Attributes

Attribute Description
name The name of the object instance from which the property is
obtained.

property Name of the property to get

Faculty of Computer Science


Other Standard Actions

Action Description
<jsp:include> Dynamically includes another resource in a JSP. When the JSP
executes, the referenced resource is included and processed.
It allows to include both static and dynamic resource.
<jsp:forward> Forwards request processing to another JSP or servlet page.
This action terminates the current JSP’s execution.
<jsp:param> To pass additional parameter, name/value pairs of information,
to other actions for use by these actions.
Used with the include, forward and plugin actions.
<jsp:plugin> To provide support for including a Java applet in a JSP page if
you have java applets that are part of your application.

Faculty of Computer Science


Syntax for Other Standard Actions
<jsp:include page="relative URL”/>
<jsp:include page=“banner.jsp"/>
<jsp:forward page = "Relative URL" />
<jsp:forwad page=“processing.jsp"/>

<jsp:param name="parametername" value="parametervalue>


<jsp:forward page=“processing.jsp">
<jsp:param name=“process_id" value=“1001”/>
<jsp:forward/>
<jsp:plugin type= "applet" code= "nameOfClassFile“
codebase= "directoryNameOfClassFile" />
<jsp:plugin type = "applet" code = "MyApplet.class"
codebase = “classDir" >
Faculty of Computer Science
Practice Application Design: Student Registration
mypack
Student
rollno
name
pages pages
university
register.jsp display.jsp
form.jsp
s1
Name: Ma Ma
Roll No 101 rno rollno=101
forward Roll No: 101
request name= Ma Ma University: CU
Name Ma Ma name
university= CU

Register

Faculty of Computer Science


mputer Science

Student.java

package mypack; public void setName(String name){


this.name=name;
public class Student implements java.io.Serializable }
{ public String getName(){
return name;
private int rollno; }
private String name;
public void setUniversity(String university)
private String university; {
public Student(){} this.university=university;
}
public void setRollno(int rollno){ public String getUniversity(){
this.rollno=rollno;} return university;
} }
public int getRollno(){return rollno; }
51
mputer Science

form.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<html>
<body>
<form action=“pages/register.jsp">
Roll No:<input type="text" name="rno"/><br>
Name: <input type="text" name="name" /><br>
<input type="submit" value="Register"/>
</form>
</body>
</html>

52
Faculty of Computer Science
register.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<html>
<body>
<jsp:useBean id="s1" class="mypack.Student" scope="session“/>
<jsp:setProperty name="s1" property="rollno“ param=“rno”/>
<jsp:setProperty name="s1" property="name" />
<jsp:setProperty name="s1" property=“university" value=“CU"/>
<jsp:forward page=“display.jsp”/>
</body></html>

53
Faculty of Computer Science
display.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<html>
<body> Name: Ma Ma
<jsp:useBean id="s1" class="mypack.Student" scope="session"/> Roll No: 101
University: CU
Name: <jsp:getProperty name="s1" property=“name”/> <br>
Roll No:<jsp:getProperty name="s1" property="rollno"/> <br>
University: <jsp:getProperty name="s1" property=“university"/>
<br>
</body>
</html>

54
Faculty of Computer Science
Deployment

55
Implicit Objects

• Implicit objects are created by container during the translation phase and there is
no need for the JSP author to declare first to access these objects.
• They are made available as standard variables to scripting languages as well as to
expression language.
• Each implicit object corresponds to classes defined in Servlet
• There are nine implicit objects and created in four JSP Scopes:

page
request
session
application
Faculty of Computer Science
JSP Scopes

• Page scope
• Objects that exist only in page in which they are defined
• Each JSPh has its own instance of implicit object with page scope
• Request scope
• Objects exist for duration of client request
• Objects go out of scope after response sent to client
• Session scope
• Objects exist for duration of client’s browsing session
• Objects go out of scope when client terminates session or when
session timeout occurs
• Application scope
• Objects owned by the container application
• Any servlet or JSP can manipulate these objects
Faculty of Computer Science
Faculty of Computer Science
JSP Scopes
Demonstration

Page 1 request Page 2 Page 3 request Page 4 forward Page 5

Page scope Page scope

request scope

session scope

application scope

58
Page Scope Implicit Objects

No Implicit Description
Object
1 page This object is simply a synonym for the this reference for the current
JSP instance.
2 pageContext This object can be used to set, get or remove attribute to/from one of
the four scopes.
3 response This object represents the response to the client. It can be used to add
or manipulate response such as redirect response to another resource,
send error, etc.,

Faculty of Computer Science


Page Scope Implicit Objects Con’t

No Implicit Description
Object
4 out This object writes text as part of the response to a request.
This object is used implicitly with JSP expressions and JSP actions and
inserts string content in a response
5 exception This object represents the exception that is passed to the JSP error page.
This object can be used to print the exception and available only in a
JSP error page.
6 config This object represents the JSP configuration options. This object can be
used to get initialization parameter for a particular JSP page.
The config object is created by the web container for each JSP page.

Faculty of Computer Science


Implicit Objects in Other Scopes
No Implicit Description
Object
Request Scope
1 request This object is created for every request. It can be used to get request
information and to to set, get and remove attributes from the JSP request
scope.
Session Scope
2 session This object can be used to set, get or remove attribute in session scope or to
get session information. This object is available only in pages that
participate in a session.
Application Scope
3 application This object represents the web application in which current JSP executes.
This object can be used to get initialization parameter from configuration
file (web.xml). It can also be used to get, set or remove attribute from the
application scope. Faculty of Computer Science
Practice Application Design: Student Information
web.xml
<context-param>
University=“CU”

pages pages
form.jsp getInfo.jsp display.jsp

RollNo rno <session scope> Student Info:sinfo


sinfo=RollNo-Name include University:.....
Name name request
Start Time:.....
Register

Faculty of Computer Science


Faculty of Computer Science
form.jsp

63
Faculty of Computer Science
web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app>

<context-param>
<param-name>university</param-name>
<param-value>CU</param-value>
</context-param>

<welcome-file-list>
<welcome-file> form.jsp </welcome-file>
</welcome-file-list>

</web-app>
64
Faculty of Computer Science
getInfo.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1” %>
<html>
<body>
<%
String sinfo=request.getParameter("rno")+"-"+request.getParameter("name");
session.setAttribute("stuinfo",info);
//pageContext.setAttribute("stuinfo", info,pageContext.SESSION_SCOPE);

%>
<jsp:include file=“display.jsp”/>
</body> </html>

65
Faculty of Computer Science
display.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1“ import=“java.util.Date” %>
<html>
<body>
<%

out.println("Student Info:"+session.getAttribute("stuinfo")+"<br>");

out.println("Univrsity:"+application.getInitParameter("university")+"<br>");

out.println(“Start Time:"+new Date(session.getCreationTime())+"<br>"); %>


</body>
</html>

66
Faculty of Computer Science
Deployment

67
What is Expression Language (EL) ?

• Expression language (EL) has been introduced in JSP 2.0.


• EL allows page authors to use simple expressions to dynamically access data from
bean properties and other implicit objects
• EL includes arithmetic, relational and logical operators too.
• Syntax of EL:
${expression}
• Whatever present inside braces gets evaluated as a single value at runtime and
being sent in the output of the JSP or passed as a value to a JSP action

68 Faculty of Computer Science


Using EL in JSP

• To enable the EL expression in a JSP, developers need to use following page


directive.
• <%@ page isELIgnored="false"%>
• EL expression can be used in different ways in a JSP page:
1. As attribute values in standard and custom tags.
<jsp:include page="${location}">
2. To set a properties value
<jsp:setProperty name=“stu" property=“name“ value="${stuName}" />
3. To output in HTML tag
<h1>Welcome ${userName}</h1>

69 Faculty of Computer Science


Most Frequently used Operators in EL
Operator Description
.(dot) Access a bean property or get value of key in a Map
[] Same with dot operator but can be also used to access an
array or a list by specifying an index
() Group a subexpression to change the evaluation order
empty Test for empty variable value
+ , - , * , / or div, Arithmetic operators
% or mod
== or eq , != or ne ,
< or lt, > or gt , Comparison operators
<= or le , >= or ge
&& or and, || or or Logical operators
! or not
70 Faculty of Computer Science
EL Operator Usage Examples
EL Expression Result
${s1.name} The value of name property of object s1
${s1[‘name’]} The value of name property of bean s1
${students[‘stu_rno’]} The value of the entry named stu_rno in the students map
${(1+2)/4} 0.75
${empty s1.name} True if name property of object s1 is null or empty string
${(9-2*4) mod 3} 1
${10.0 eq 10} True
${(10*10) != 100} False
${‘a’ < ‘b’} True
${! 3>=4 } True
${“cat” gt “mat”} False
${5>=4 && 5>=6 } False
71
${5>=4 or 5>=6 } True Faculty of Computer Science
EL Implicit Objects

Implicit Object Description


pageScope It provides the attribute associate within pageScope.
requestScope Fetches the attribute associated with request object.
sessionScope Fetches the attribute associated with session object.
applicationScope Fetches the attribute associated with application object.
param It retrieves the single value associated with request parameter.
header It retrieves the single value associated with header parameter.
cookie It is used to get the value of cookies.
initParam It is used to map an initialize parameter.

72 Faculty of Computer Science


Practice 1: Design

Student
rno
name
uni

form.jsp register.jsp display.jsp


s1 Welcome, Ma Ma
Roll No 101 rollno rno=101 Your registration...
request name= Ma Ma forward
Name Ma Ma na Name: Ma Ma
uni= CU Roll No: 101
Register University: CU

73 Faculty of Computer Science


Practice 1: Student Class

Student

- rno: int
- name: String
- uni: String

+ Student( )
+ Getters
+ Setters

74 Faculty of Computer Science


Practice 1:form.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1” %>
<html>
<body>
<form action=“register.jsp">
Enter Name:<input type="text" name="na" /><br/>
Enter Roll No:<input type="text" name=“rno" /><br/>
<input type="submit" value=“Go"/>
</form>
</body></html>

75 Faculty of Computer Science


Practice 1: register.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1 %>
<html><head>
</head><body>

<jsp:useBean id=“stu” class=“mypack.Student” scope=“request”/>


<jsp:setProperty name=“stu” property=“rno” value=“${param.no}”/>
<jsp:setProperty name=“stu” property=“name” value=“${param.na}”/>
<jsp:setProperty name=“stu” property=“uni” value=“CU”/>

<jsp:forward page=“display.jsp”/>

</body> </html>

76 Faculty of Computer Science


Practice 1: display.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1” %>
<html>
<body>
<h2> Welcome, ${ stu[‘name’] } ! </h2>
Your Registration information are as follow: <br><br>

Name: ${stu.name} <br>


Roll No: ${stu.rno} <br>
Univeristy: ${stu.uni}<br>

</body>
</html>

77 Faculty of Computer Science


Practice 2: Design

index.jsp
example.jsp
Cookie(sid: session ID)
Page_Attribute(inPage:example.jsp)
Session_Attribute(subject:General)
Application_Attribute(title:Lesson One $$@@##
include $$@@@@###
Host name: 8080
Title:Lesson One
Subject: General

78 Faculty of Computer Science


Practice 2: Design Con’t

examples.jsp

The session id is 52201062F2944C65E88FC867477BF1D1


(1+5)/4= 1.5
(9-2*4) % 3= 1
1+2-3*4/5 = 0.6000000000000001
"Title attribute is empty is" false
"3 is not greater than or equal to 4 is" true
"cat greater than mat" is false
"(10*10) equals to 100" is true

79 Faculty of Computer Science


Practice 2 :index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1 %>
<html><head>
</head><body>
<%
Cookie mycookie=new Cookie("sid",session.getId());
response.addCookie(mycookie);
pageContext.setAttribute("inPage", "examples.jsp");
session.setAttribute(“subject”, “General”);
application.setAttribute(“title”, “Lesson One”);
%>
Host name: ${header["host"]} <br>
Title: ${applicationScope.title} <br>
Subject: ${sessionScope.subject} <br>

<jsp:include page=“${inPage}”/>
</body></html>
80 Faculty of Computer Science
Practice 2: examples.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-


1" pageEncoding="ISO-8859-1 %>
<html><head>
</head><body>
The session id is ${cookie.sid.value} <br>
(1+5)/4= ${(1+5)/4 } <br>
(9-2*4) % 3= ${(9-2*4) mod 3}<br>
1+2-3*4/5 = ${1+2-3*4/5}
“Title attribute is empty is” ${empty title} <br>
“3 is not greater than or equal to 4 is” ${! (3>=4) } br>
“cat” greater than “mat” is ${“cat” gt “mat”} <br>
“(10*10) equals to 100” is ${(10*10) eq 100} <br>
</body></html>

81 Faculty of Computer Science


Exception

• Exception is an run-time error which arises during the execution of java program.
• These are some conditions where an exception occurs:
• A user has entered invalid data.
• The file requested to be accessed does not exist in the system.
• A file that needs to be opened cannot be found.
• When the Java Virtual Machine (JVM) runs out of memory.
• Network drops in the middle of communication.

82 Faculty of Computer Science


Purpose of Exception Handling

• The purpose of exception handling is to detect and report an exception so that


proper action can be taken and prevent the program which is automatically
terminate or stop the execution because of that exception.

83 Faculty of Computer Science


Exception Hierarchy

84 Faculty of Computer Science


Types of Java Exceptions

• There are mainly two types of exceptions: checked and unchecked. Here, an error
is considered as the unchecked exception.
1. IOException or Checked Exception
2. Runtime Exception or Unchecked Exception
3. Error

(1) IOException or Checked Exception


• Exceptions that must be included in a method’s throws list if that method can generate
one of these exceptions and does not handle it itself.
• These are called checked exceptions.
• For example, if a file is to be opened, but the file cannot be found , an exception
occurs.
• These exceptions cannot simply be ignored at the time of compilation.

85 Faculty of Computer Science


Types of Java Exceptions(Cont’d)

(2) Runtime Exception or Unchecked Exception


• Exceptions need not be included in any method’s throws list.
• These are called unchecked exceptions because the compiler does not check to see if a
method handles or throws these exceptions.

(3) Error
• Errors are not normally trapped form the Java programs.
• These conditions normally happen in case of severe failures, which are not handled
by the java programs.
• Errors are generated to indicate errors generated by the runtime environment.
• Example : JVM is out of Memory. Normally programs cannot recover from errors.

86 Faculty of Computer Science


Exception Handling in JSP

• In JSP, there are two ways to perform exception handling:


• By errorPage and isErrorPage attributes of page directive
• By <error-page> element in web.xml file

87 Faculty of Computer Science


Handling Exception using page directive attributes

• The page directive in JSP provides two attributes to be used in exception handling.
They’re:
• errorPage: Used to site which page to be displayed when exception occurred.

Syntax :
<%@page errorPage="url of the error page"%>

• isErrorPage : Used to mark a page as an error page where exceptions are


displayed.
Syntax :
<%@page isErrorPage="true"%>
88 Faculty of Computer Science
Example of exception handling in jsp by the elements of
page directive
• create a page to handle the exceptions, as in the error.jsp page.
• The pages where may occur exception, define the errorPage attribute of page
directive, as in the process.jsp page.
• There are 3 files:
1. index.jsp for input values
2. process.jsp for dividing the two numbers and displaying the result
3. error.jsp for handling the exception

89 Faculty of Computer Science


index.jsp

<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"/> Output
</form>

90 Faculty of Computer Science


process.jsp

<%@ page errorPage="error.jsp" %>


<%
String num1=request.getParameter("n1"); Output
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);
%>

91 Faculty of Computer Science


error.jsp

<%@ page isErrorPage="true" %>


<h3>Sorry an exception occured!</h3>
Exception is: <%= exception %> Output

92 Faculty of Computer Science


Handling Exceptions Using error-page Element
web.xml File
• This is another way of specifying the error page for each element, but instead of using the
errorPage directive, the error page for each page can be specified in the web.xml file,
using the <error-page> element.
Syntax:
<web-app>

<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>

</web-app>

93 Faculty of Computer Science


Exception handling in jsp by specifying the error-page
element in web.xml file
• There are 4 files
1. web.xml file for specifying the error-page element
2. index.jsp for input values
3. process.jsp for dividing the two numbers and displaying the result
4. error.jsp for displaying the exception

94 Faculty of Computer Science


Example of exception handling in jsp

• index.jsp and error.jsp are the same the elements of page directive
process.jsp
<%@ 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);

%>

95 Faculty of Computer Science


Output of Error Page

96 Faculty of Computer Science


What is a Custom Tag Library?

• collection of custom actions (tags) made available in a JSP page


• standardized to be portable between different JSP containers
• make it possible to write JSP pages without the use of scripting
• elements (embedded java fragments of code)
• code is easier to maintain
• logic is separated from presentation
• web designer role separated from java developer

97 Faculty of Computer Science


JavaServer Pages Standard Tag Library (JSTL)

• The JSP Standard Tag Library (JSTL) is a collection of custom tag libraries .
• Core Tag Library – looping, expression evaluation, basic input/output
• Formatting/Internationalization Tag Library – parsing data, such as dates.
• Database Tag Library – tags that can be used to access SQL databases
• XML Tag Library – tags can be used to access XML elements
• To use any of these libraries in a JSP, need to declare using the taglib directive in
the JSP page, specifying the URI and the Prefix
Core <@tablib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core %>
XML <@tablib prefix=“c” uri=“http://java.sun.com/jsp/jstl/xml %>
Formatting <@tablib prefix=“c” uri=“http://java.sun.com/jsp/jstl/fmt %>
Database <@tablib prefix=“c” uri=“http://java.sun.com/jsp/jstl/sql %>

98 Faculty of Computer Science


Declaring a Custom Tag Library

99 Faculty of Computer Science


Declaring a Custom Tag Library

• A URI is a string that tells the container how to locate the TLD file for the library,
where it finds the tag file name or java class for all actions in the library
• when the web server is started
• it locates all TLD files,
• for each of them gets the default URI
• create a mapping between the URI and the TLD
• a default URI must be a globally unique string

100 Faculty of Computer Science


Installing Custom Tag Libraries

• Download Standard 1.2 Taglib zip file


• http://www.java2s.com/Code/Jar/j/Downloadjstl12jar.htm
• Unzip into directory of your choice (e.g.,C:\jakarta-taglibs).
• Copy \lib\jstl.jar to the WEB-INF\lib directory of your Web application

101 Faculty of Computer Science


Core Library Tags - Listing

102 Faculty of Computer Science


Flow Control: <c:forEach> tag

• The JSTL <c:forEach> Core Tag is used when a block of statements is executed
again and again.
• It works same as for loop in java.
Syntax:
<c:forEach var="counterVar" begin="startValue" end="endValue">
//Block of statements
</c:forEach>

103 Faculty of Computer Science


Example: JSP page using JSTL that outputs 1 to 10 on a
webpage
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
<head> A tag lib directive
<title><c:forEach> Tag Example</title> declare use of core
library
</head>

<body>
<c:forEach var = "i" begin = "1" end = "5">
Item <c:out value = "${i}"/><p>
</c:forEach>
</body>
</html>
JSTL Tag Examples
104 Faculty of Computer Science
Output Tags : <c:out>

• adds the value of the evaluated expression to the response buffer


Syntax 1:
<c:out value=“expression”
[excapeXml=“true|false”]
[default=“defaultExpression”] />
Syntax 2:
<c:out value=“expression”
[excapeXml=“true|false”]>
defaultExpression

</c:out>

105 Faculty of Computer Science


JSTL Example: <c:out> tag

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


<html>
<head>
<title>c:out JSTL core tag example</title>
</head>
<body>
<c:out value="This is a c:out JSTL core tag example."/><br/>
Sum of 10 and 20 = <c:out value="${10+20}"/><br/><br/>
<c:out value="${'<h6>This is a
<c:out> escape XML test </h6>'}"/>
</body>
</html>
106 Faculty of Computer Science
Variable Support: <c:set>

<c:set> tag
• c:set allows to set the result of an expression in a variable within a given scope.
• Using this tag helps to set the property of 'JavaBean' and the values of the
'java.util.Map' object.
• JSTL <c:set> tag is similar to the <jsp:setProperty> JSP action tag
• but this JSP action tag only allows setting the bean property and cannot set the
value of a map key or create a scope variable.
Syntax
<c:set attributes />

107 Faculty of Computer Science


JSTL Example: <c:set>

• an example where this <c:remove> tag removes a variable from the session's scope, but first, this
variable must exist within the session. So here we are going to set a session variable using the
<c:set> tag.
Example :<c:set>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Core Tag Example</title>
</head>
<body>
<c:set var="Income" scope="session" value="${4000*4}"/>
<c:out value="${Income}"/>
</body>
</html>

108 Faculty of Computer Science


URL:<c:url> tag

<c:url>
 applies encoding and conversion rules for a relative or absolute URL
Rules:
 URL encoding of parameters specified in <c:param> tags
 context-relative path to server-relative path
 add session Id path parameter for context- or page-relative path

Syntax:
<c:urlurl=“url” [context=“externalContextPath”]
[var=“var”]
scope=“page|request|session|application” >
<c:param> actions

</c:url>

109 Faculty of Computer Science


JSTL Example: <c:url> tag

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


<html>
<head>
<title>Core Tag Example</title>
</head>
<body>
<c:url value="/RegisterDao.jsp"/>
</body>
</html>

110 Faculty of Computer Science


Exception Handling:<c:catch>

• It is used for Catches any Throwable exceptions that occurs in the body and
optionally exposes it.
• In general it is used for error handling and to deal more easily with the problem
occur in program.
Syntax:
<c:catch var="<string>">
...
</c:catch>

111 Faculty of Computer Science


JSTL Example: <c:catch>

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


<html>
<head>
<title>Core Tag Example</title>
</head>
<body>
<c:catch var ="catchtheException">
<% int x = 2/0;%>
</c:catch>
<c:if test = "${catchtheException != null}">
<p>The type of exception is : ${catchtheException} <br />
There is an exception: ${catchtheException.message}</p>
</c:if>
</body>
</html>

112 Faculty of Computer Science


Thank You

©https://blogs.ashrithgn.com/

You might also like