0% found this document useful (0 votes)
42 views24 pages

EJ Unit 3

Uploaded by

Yexo Kaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views24 pages

EJ Unit 3

Uploaded by

Yexo Kaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Enterprise Java

MODULE-3: Introduction to Java Server Pages

Vidyalankar School of Compiled by: Prof. Beena Kapadia


Information Technology
Wadala (E), Mumbai [email protected]
www.vsit.edu.in
Certificate
This is to certify that the e-book titled “Enterprise java” comprises
all elementary learning tools for a better understating of the relevant concepts. This
e-book is comprehensively compiled as per the predefined eight parameters and
guidelines.

Signature
Date: 09-07-2019
Ms. Beena Kapadia
Assistant Professor
Department of IT
DISCLAIMER: The information contained in this e-book is compiled and distributed for
educational purposes only. This e-book has been designed to help learners understand
relevant concepts with a more dynamic interface. The compiler of this e-book and
Vidyalankar Institute of Technology give full and due credit to the authors of the contents,
developers and all websites from wherever information has been sourced. We acknowledge
our gratitude towards the websites YouTube, Wikipedia, and Google search engine. No
commercial benefits are being drawn from this project.
Unit 3: Introduction to JSP

Contents:
Introduction to Java Server Pages:
1. Why use Java Server Pages?
2. Disadvantages of JSP
3. JSP v\s Servlets
4. Life Cycle of a JSP Page
Getting Started with Java Server Pages:
1. Comments
2. JSP Document
3. JSP Elements
4. JSP GUI Example.
Action Elements:
1. Including other Files
2. Forwarding JSP Page to Another Page
3. Passing Parameters for other Actions
4. Loading a Javabean.
Implicit Objects, Scope and El Expressions:
1. Implicit Objects
2. Character Quoting Conventions
3. Unified Expression Language [Unified El]
4. Expression Language.
Java Server Pages Standard Tag Libraries:
1. What is wrong in using JSP Scriptlet Tags?
2. How JSTL Fixes JSP Scriptlet's Shortcomings?
3. Disadvantages Of JSTL
4. Tag Libraries.
Recommended Books
Books:
B1 Java EE 7 For Beginners by Sharanam Shah, Vaishali Shah

Prerequisites & Linking


Unit III Sem I Sem II Sem. III Sem. IV Sem. VI

Introduction to Java script OOPS with OOPS Core Java Project on


JSP, EL and JSTL C++ MVC

Introduction to Java Server Pages:

Why use Java Server Pages?

The benefits of using JSP:


 Nobody Can Borrow The Code:
1] When a website that does something really cool, which attracts the attention of the users,
developers look at the source code of the page and copy the JavaScript or other code into their
own pages which then do the same cool stuff.
2] With JSP, this issue does not arise at all. The code written runs and remains on the Web
server. All of its functionality is handled before the page is sent to a browser.
 Faster Loading Of Pages:
1] When DHTML,JavaScript or any other client-side technology is used to customize page
content,the page developer must send all of the content that a user might want plus the code that is
necessary to hide and reveal those sections.
2] With JSP,decisions can be made about what the user want to see at the Web server prior the
pages being dispatched.Hence,only the content that the user is interested in will be dispatched to the
user,with no extra code and extra content.
 No Browser Compatibility Issues:
1] Those who craft JavaScript or other scripts know that the code should always be checked
thoroughly across several versions of several browsers to make sure it will work as expected.
2] The most common browsers are Mozilla Firefox,Internet Explorer and Chrome.Making
JavaScript work in all these browsers requires either things are kept very simple or custom code is
created for multiple versions os some of the browsers and delivered appropriately.
3] JSP has no such issues.The developers ends up sending standard HTML to a user browser.This
largely eliminates scripting issues and cross browser compatibility.
 JSP Support:
1] JSP is supported by a number of Web servers.Built-in support for JSP is available in java Web
Server from Oracle.
2] For Web servers that do not directly support JSP and Java Servlets,add-on support is provided
through products such as live Software’s JRun[recently acquired by Allaire].JRun works with a number
of popular Web servers like Apache,Microsoft IIS and PWS and Enterprise Web servers and others.
 Compilation:
1] Another important benefit is that the JSP is always compiled before the web server processes
it.The older technologies such as CGI require the server to load an interpreter and the target script
each time the page is requested.
2] JSP gets around this problem by compiling each JSP page into executable code the first time it
is requested and invoking the resulting code directly on all subsequent requests.When coupled with a
persistent JVM on a Java enabled web server,this allows the server to handle JSP pages much faster.

Disadvantages of JSP
 Attractive Java Code
o Putting Java code spec within a web page is really bad design, but JSP makes it
tempting to do just that.
 Java Code Required
o To do simple things in JSP can actually demand putting Java code in a page.
 Simple tasks are hard to code.
o Even including simple page headers and footers is a bit difficult with JSP.
o Additionally, the /header.jsp and /footer.jsp must be made publicly accessible
somewhere under the document root even though they are not full pages themselves.
 Difficult Looping in JSP
o Looping is difficult in JSP. Here’s the JSP code that loops through a vector od ISP
objects and prints out the name of each:
<%
Enumeration e = list.elements();
while (e.hasMoreElements()) {
out.print("The next name is ");
out.println(((ISP)e.nextElement()).getName());
out.print("<br>");
}
%>
 Occupies a lot of space
o For every 30K JSP file on the Web server there will be a corresponding much larger
class file created.
o This essentially more than doubles the hard drives space requirements to store JSP
pages.

JSP v\s Servlets

JSP Servlets
Servlets are Java programs that are
JSP is a webpage scripting language that
already compiled which also
can generate dynamic content.
creates dynamic web content.
In MVC(Model View Controller), jsp act as a In MVC(Model View Controller),
view. servlet act as a controller.
It’s easier to code in JSP than in Java
Its little much code to write here.
Servlets.
servlets are best for use when there
JSP are generally preferred when there is
is more processing and
not much processing of data required.
manipulation involved.
JSP run slower compared to Servlet as it
Servlets run faster compared to
takes compilation time to convert into Java
JSP.
Servlets.
The advantage of JSP programming over
There is no such custom tag facility
servlets is that we can build custom tags
in servlets.
which can directly call Java beans.
We can achieve functionality of JSP at
There are no such methods for
client side by running JavaScript at client
servlets.
side.

Life Cycle of a JSP Page


When a web container or servlet container receives a request from client for a jsp page, it takes the
jsp through its various life cycle phases, and then returns the response to the client. What all things
these containers should support, is defined by the jsp and servlet specifications. The web
containers can be a part of web servers, e.g. tomcat, and application servers.
Following diagram shows the different stages of life cycle of jsp. Broadly, these stages can be
classified into three.
 Instantiation
 Request Processing
 Destruction
Life Cycle of JSP
1) Instantiation:
When a web container receives a jsp request (may be first or subsequent), it checks for the
jsp’s servlet instance.If no servlet instance is available or if it is older than the jsp, then, the web
container creates the servlet instance using following stages.
a) Translation
b) Compilation
c) Loading
d) Instantiation
e) Initialization
a) Translation:
Web container translates (converts) the jsp code into a servlet code. This means that jsp is
actually a servlet. After this stage, there is no jsp, everything is a servlet. This task will create a
complete jsp page, by considering all included components. Here on, the static content and
dynamic contents are treated differently. The resultant is a java class instead of an html page.
b)Compilation:
The generated servlet is compiled to validate the syntax. As it is a java class, the compilation
is done using javac command. This will generate the byte code to be run on JVM.
c)Loading:
The compiled byte code is loaded by the class loader used by web container. This is a
standard process of using any java class.
d)Instantiation:
In this step, instance of the servlet class is created so that it can serve the request.
e)Initialization:
Initialization is done by calling the jspInit() method. This is one time activity at the start of the
initialization process. Initialization will make the ServletContext and ServletConfig objects
available. One can access many attributes related to the web container and the servlet itself.
After initialization the servlet is ready to process requests.
2) Request Processing:
Entire initialization process is done to make the servlet available in order to process the
incoming request. jspService() is the method that actually processes the request. It prints the
response in html (any other) format, using ‘out’ object.
3) Destroy:
Whenever the server is shutting down or when the server needs memory, the server removes
the instance of the servlet. The destroy method jspDestroy() can be called by the server after
initialization and before or after request processing. Once destroyed the jsp needs to be
initialized again.
Just to summarize, web container handles incoming requests to a jsp by converting it into a
servlet and then by using this servlet to generate the response. Also when the server shuts down,
the container needs to clear the instances.

Getting Started With Java Server Pages:


1. Comments
2. JSP Document
3. JSP Elements
4. JSP GUI Example.

Directives with syntax in JSP Pages and JSP Documents.


o The jsp directives are messages that tells the web container how to translate
a JSP page into the corresponding servlet.
o There are three types of directives:
 page directive
 include directive
 taglib directive

o Syntax of JSP Directive


<%@ directive attribute="value" %>

The page directive defines attributes that apply to an entire JSP page.

Syntax of JSP page directive


<%@ page attribute="value"… %>
1. JSP Include directive
o The include directive is used to include the contents of any resource it may be jsp file,
html file or text file. The include directive includes the original content of the included
resource at page translation time (the jsp page is translated only once so it will be
better to include static resource).
Advantage of Include directive
Code Reusability
Syntax of include directive
<%@ include file="resourceName" %>
Example of include directive
o In this example, we are including the content of the header.html file. To run this
example you must create an header.html file.
<html> <body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body> </html>

2. JSP Taglib directive


o The JSP taglib directive is used to define a tag library that defines new tags. We use
the TLD (Tag Library Descriptor) file to define the tags. In the custom tag section,
we will use this tag so it will be better to learn it in custom tag.
Syntax JSP Taglib directive
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary"%>

Example of JSP Taglib directive


o In this example, we are using our tag named currentDate. To use this tag we must
specify the taglib directive so the container may get information about the
tag.
<html>
<body>
<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
<mytag:currentDate/>
</body>
</html>

JSP Elements.
If you want to put any java code in that file then you can put it by the use of jsp tags(elements).
There are mainly three groups of jsp tags(elements) available in java server page:
1. JSP scripting elements
1.1 JSP scriptlet tag
1.2 JSP expression tag
1.3 JSP declaration tag
1.4 Comment tag
2. JSP directive elements
2.1page directive
2.2 include directive
2.3 taglib directive
3. JSP standard action elements
3.1 .<jsp:forward>
3.2. <jsp:include>
3.3 <jsp:param>

1:-JSP scripting elements


The scripting elements provides the ability to insert java code inside the jsp. JSP Scripting element
are written inside <% %>tags. These code inside <% %> tags are processed by the JSP engine
during translation of the JSP page. Any other text in the JSP page is considered as HTML code or
plain text.
There are four types of scripting elements:
 scriptlet tag
 expression tag
 declaration tag
 Comment tag
scriptlet tag
 A scriptlet is a valid code in java and is placed in the jspService() method of the JSP engine at
the time of running. The scriplet syntax is -
<% java code %>
There are variables available exclusively for the scriplets. They are request, response, out,session and
pageContext, application, config and exception.
JSP expression tag
The code placed within expression tag is written to the output stream of the response. So you need
not write out.print() to write data. It is mainly used to print the values of variable or method.
Syntax of JSP expression tag
<%= statement %>
JSP Declaration Tag
The JSP declaration tag 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. So it doesn't
get memory at each request.
Syntax of JSP declaration tag
The syntax of the declaration tag is as follows:
<%! field or method declaration %>
JSP Comment
There is only one type of JSP comment available by JSP specification.
JSP Comment Syntax:
<%-- comment --%>
This JSP comment tag tells the JSP container to ignore the comment part from compilation. That is,
the commented part of source code is not considered for the content parsed for ‘response’.
2) JSP directive elements
The jsp directives are messages that tells the web container how to translate a JSP page into the
corresponding servlet.
There are three types of directives:
 page directive
 include directive
 taglib directive
Syntax of JSP Directive
<%@ directive attribute="value" %>
1:- 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
1)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.
2)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".
3)extends
The extends attribute defines the parent class that will be inherited by the generated servlet.It is
rarely used.
4)Info
This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.
5)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.
6)language
The language attribute specifies the scripting language used in the JSP page. The default value is
"java".
7)isELIgnored
We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By default its value
is false i.e. Expression Language is enabled by default.
8)isThreadSafe
Servlet and JSP both are multithreaded.If you want to control this behaviour of JSP page, you can
use isThreadSafe attribute of page directive.The value of isThreadSafe value is true.If you make it
false, the web container will serialize the multiple requests, i.e. it will wait until the JSP finishes
responding to a request before passing another request to it.
9)errorPage
The errorPage attribute is used to define the error page, if exception occurs in the current page, it
will be redirected to the error page.
10)isErrorPage
The isErrorPage attribute is used to declare that the current page is the error page.
The exception object can only be used in the error page.
2:- JSP Include directive
The include directive is used to include the contents of any resource it may be jsp file, html file or
text file. The include directive includes the original content of the included resource at page
translation time (the jsp page is translated only once so it will be better to include static resource).
Advantage of Include directive
Code Reusability
Syntax of include directive
<%@ include file="resourceName" %>

Note: The include directive includes the original content, so the actual page size grows at
runtime.
3:- JSP Taglib directive
The JSP taglib directive is used to define a tag library that defines many tags. We use the TLD (Tag
Library Descriptor) file to define the tags. In the custom tag section we will use this tag so it
will be better to learn it in custom tag.
Syntax JSP Taglib directive
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
1) JSP standard action elements
JSP actions are special XML tags which control the behavior of servlet engine. JSP actions allow you
to insert a file dynamically, reuse external JavaBean components, forward the request to the other
page and generate HTML for Java Applet Plugin.
jsp:include action
JSP include action allows you to include a file at runtime. The syntax of JSP include action is as
follows:
<jsp:include page="Relative URL" flush="true" />
jsp:useBean action
JSP useBean action lets you load a JavaBean component into the page and use it later. JSP useBean
action allows you to reuse other Java classes. The syntax of JSP useBean action is as follows:
<jsp:useBean id="objectName" class="package.class" />
jsp:forward Action
jsp:forward action allows you to forward a request to the other page. The syntax of the jsp:forward
action is listed as below. There is one attribute called page which value is a page you want to
forward the request to. You can specify the page statically or dynamically by using the expression.
<jsp:forward page="error.jsp" />
<jsp:forward page="<%= java-expression %>" />
jsp:plugin Action
jsp:plugin action allows you to embedded Java Applet into a page. Suppose you have an applet
which demonstrates the JSP page life cycle called com.jsp.jspapplet. Here is the way we use
jsp:plugin action to embedded that applet into a page:
<jsp:plugin type="applet"
code="com.jsp.jspapplet"
codebase="."
width="500"
height="400">
<jsp:fallback>
<p>Unable to use Java Plugin</p>
</jsp:fallback>
</jsp:plugin>

Directives with syntax in JSP Pages and JSP Documents.


o The jsp directives are messages that tells the web container how to translate a JSP
page into the corresponding servlet.
o There are three types of directives:
 page directive
 include directive
 taglib directive
o Syntax of JSP Directive
<%@ directive attribute="value" %>
o JSP page directive
o The page directive defines attributes that apply to an entire JSP page.
o Syntax of JSP page directive
o <%@ page attribute="value" %>

2. JSP Include directive


o The include directive is used to include the contents of any resource it may be jsp file,
html file or text file. The include directive includes the original content of the included
resource at page translation time (the jsp page is translated only once so it will be
better to include static resource).
o Advantage of Include directive
Code Reusable
o Syntax of include directive
<%@ include file="resourceName" %>
o Example of include directive
o In this example, we are including the content of the header.html file. To run this
example you must create an header.html file.
<html> <body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body> </html>

3. JSP Taglib directive


o The JSP taglib directive is used to define a tag library that defines many tags. We use
the TLD (Tag Library Descriptor) file to define the tags. In the custom tag section
we will use this tag so it will be better to learn it in custom tag.
o Syntax JSP Taglib directive
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary"%>
o Example of JSP Taglib directive
o In this example, we are using our tag named currentDate. To use this tag we must
specify the taglib directive so the container may get information about the
tag.
<html> <body>
<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
<mytag:currentDate/>
</body> </html>

Action Commands
3.1 .<jsp:forward>
3.2. <jsp:include>
3.3 <jsp:param>

3.1 jsp:forward action tag


o The jsp:forward action tag is used to forward the request to another resource it may
be jsp, html or another resource.
o Syntax of jsp:forward action tag without parameter
<jsp:forward page="relativeURL | <%= expression %>" />
o Syntax of jsp:forward action tag with parameter
<jsp:forward page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parametervalue | <%=expression%>" />
</jsp:forward>
o Example of jsp:forward action tag without parameter
In this example, we are simply forwarding the request to the printdate.jsp file.
o index.jsp
<html> <body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" />
</body> </html>
o printdate.jsp
<html> <body>
<%out.print("Todayis:"+java.util.Calendar.getInstance().getTime()); %>
</body> </html>
3.2. jsp:include action tag
o The jsp:include action tag is used to include the content of another resource it may
be jsp, html or servlet. The jsp include action tag includes the resource at request
time so it is better for dynamic pages because there might be changes in future.
o The jsp:include tag can be used to include static as well as dynamic pages.
Advantage of jsp:include action tag
Code reusability : We can use a page many times such as including header and footer
pages in all pages. So it saves a lot of time.

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
In this example, index.jsp file includes the content of the printdate.jsp file.
File: index.jsp
<h2>this is index page</h2>
<jsp:include page="printdate.jsp" /> <h2>end section of index page</h2>
File: printdate.jsp
<%out.print("Todayis:"+java.util.Calendar.getInstance().getTime()); %>
3.3 jsp:param action tag
 The <jsp:param> element is used to specify additional request parameters for the
target resource by appending parameters to the request objects. This element is
used in the body of the <jsp:forward> element of the <jsp:include> element.

 Syntax: <jsp:param name=”<ParameterName>” value=”<ParameterValue>” /> ..

Java Bean Tags


Java Bean is a java class that should follow following conventions.
 It should have a no argument constructor.
 It should be serializable.
 It should provide methods to set and get the values of the properties known as getter
and setter methods.
Why use Java Bean?
According to java White paper, it is reusable software component. A bean encapsulates many
objects, so we can access this objects from multiple places. Moreover, it provides the easy
maintenance.
Eg:-
Java Bean class
//Employee,java
Package mypack;
Public class Employee implements java.io.serialization{
Private int id;
Private String name;
Public Employee(){}
Public void setId(intId){this.id=id;
}
Public intgetId(){return id;}
Public void setName(String name)(this.name=name;}
Public string getValue(){return name;}
}
How to access the java bean class?
To access the java bean class, we should use getter and setter methods.
Package mypack;
Public class Test{
Public static void main(string args[])
{
Employee=new Employee();
e.setName(“john”);
System.Out.Println(e.getName());
}
}
GUI Example
Write a JSP file to get a feedback from index file (name, message) which also accepts header
from another file using JSP document.
Index.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="test.jsp" method="POST">
Name:<input type="text" name="t1" value="" />
Message:<input type="text" name="t2" value="" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

test.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%@include file="header.html" %>
<% String name,msg;
name=request.getParameter("t1");
msg=request.getParameter("t2");
%>
<h2> Your name is <%=name%><br>
Your Message is:<%=msg%>
</h2>
</body>
</html>
header.html
<h1>This is a Header</h1>

Implicit Objects.
JSP Implicit objects are created by the web container. These implicit objects are Java objects.that
implement interfaces in the Servlet and JSP API. Scripting elements in a JSP page canmake use of
these JSP implicit objects. There are nine (9) JSP implicit objects available.
JSP Implicit Objects are as follows:
1. Request Implicit Object: The JSP implicit request object is an instance of a java class that
implements thejavax.servlet.http.HttpServletRequest interface. It represents the request made
by the client. The request implicit object is generally used to get request parameters, request
attributes, header information and query string values.
Eg.<html>
<body bgcolor=’#00CCFF’>
<h2>Welcome<%=request.getParameter(“username”)%>!</h2>
</body>
</html>
2. Response implicit object: The JSP implicit response object is an instance of a java class that
implements the javax.servlet.http.HttpServletResponse interface. It represents the response to
be given to the client. The response implicit object is generally used to set the response
content type, add cookie and redirect the response.
Eg. Index.html:
<form action=”welcome.jsp”>
<input type=”text” name=”uname”>
<input type=”submit” value=”go”><br>
Welcome.jsp: <% response.sendRedirect(“http://www.google.com”);
3. out Implicit Object: The JSP implicit out object is an instance of the javax.servlet.jsp.JspWriter
class. It represents the output content to be sent to the client. The out implicit object is used to
write the output content.
Eg.<html>
<body>
<% out.print(“Today is:”+java.util.Calender.getInstance().getTime());%>
4. Session Implicit Object: The JSP implicit session object is an instance of a java class that
implements the javax.servlet.http.HttpSession interface. It represents a client specific
conversation. The session implicit object is used to store session state for a single user.
Eg. Index.html
<html>
<body>
<form action=”welcome.jsp”>
Enter User Name:<input type=”text” name=”uname”>
<input type=”submit” value=”go”><br/>
</form> </body></html>
Welcome.jsp
<html>
<body>
<% String name=request.getParameter(“uname”);
Out.print(“welcome”+name);
session.setAttribute(&quot;user&quot;,name);
< a href=”second.jsp”>second jsp page</a>
%>
</body>
</html>
second.jsp
<html>
<body>
<% String name=(String)session.getAttribute(“user”);
out.print(“Hello”+name);
%> </body> </html>
5. application Implicit object: The JSP implicit application object is an instance of a java class
that implements the javax.servlet.ServletContext interface. It gives facility for a JSP page to
obtain and set information about the web application in which it is running.
6. exception Implicit object: The JSP implicit exception object is an instance of the
java.lang.Throwable class. It is available in JSP error pages only. It represents the occured
exception that caused the control to pass to the JSP error page.
Eg. Index.jsp
<form action=”process.jsp”>
No1:<input type=”text” name=”n1” /><br><br>
No2:<input type=”text” name=”n2” /><br><br>
<input type=”submit” value=”divide”/>
process.jsp
<%@ page errorPage=”error.jsp”%>
<%
int a=Integer.parseInt(request.getParameter(“n1”));
Int b=Integer.parseInt(request.getParameter(“n2”));
Int c=a/b;
out.print(“division of number is”+c);
%>
error.jsp
<%@ page isErrorPage=”true” %>
<h3>An exception occurred!</h3>
Exception is<%=exception%>
7. Config Implicit object: The JSP implicit config object is an instance of the java class that
implements javax.servlet.ServletConfig interface. It gives facility for a JSP page to obtain the
initialization parameters available.
8. page Implicit object: The JSP implicit page object is an instance of the java.lang.Object class.
It represents the current JSP page. That is, it serves as a reference to the java servlet object that
implements the JSP page on which it is accessed. It is not advisable to use this page implict
object often as it consumes large memory.
9. pageContext Implicit object: The JSP implicit pageContext object is an instance of the
javax.servlet.jsp.PageContext abstract class. It provides useful context information. That is it
provides methods to get and set attributes in different scopes and for transfering requests to
other resources. Also it contains the reference to to implicit objects.
Index.html
<html>
<body>
<form action=”welcome.jsp”>
<input type=”text” name=”uname”>
<input type=”submit” value=”go”><br/>
</form> </body> </html>
Welcome.jsp
<html>
<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
<html>
<body>
<% String name=(String)pageContext.getAttribute(“user”,name,PageContext.SESSION_SCOPE);
out.print(“Hello”+name);
</body> </html>

Implicit Objects in JSP


Source: https://www.youtube.com/watch?v=mhrDVzj8pQM
Character Quoting Conventions
 Because certain character sequences are used to represent start and stop tags, the developer
sometimes needs to escape a character so the JSP engine does not interpret it as part of a
special character sequence
 In a scripting element, if the character ‘%>’ needs to be used, escape the greater than sign
with a backslash.
<% String message = “This is the %/> message” ; %>
 The backslash before the expression acts as an escape character, informing the JSP engine to
deliver the expression verbatim instead of evaluating it.
 There are a number of special constructs used in various cases to insert characters that
would otherwise be treated specially,they are as follows:
Escape Characters Description
\’ A single quote in an attribute that uses
single quotes.
\” A double quote in an attribute that uses
double quotes.
\\ A backslash in an attribute that uses
backslash.
%\> Escaping the scripting end tag with a
backslash.
<\% Escaping the scripting start tag with a
backslash.

Types of Unified Expression Language [Unified El]


 The Expression Language (EL) provides a way to simplify expressions in JSP. It is a simple
language used for accessing implicit objects and Java classes, and for
manipulating collections in an elegant manner. EL provides the ability to use run-
time expressions outside of JSP scripting elements.
 JavaServer Pages each has its own expression language. The expression language
included in JSP provides greater flexibility to the web application developer. Deferred
evaluation means that the technology using the unified EL takes over the
responsibility of evaluating the expression from the JSP engine and evaluates the
expression at the appropriate time during the page lifecycle. But the JSP EL is designed
for immediate evaluation of expressions.
 The Expression Language (EL) simplifies the accessibility of data stored in the Java Bean
component, and other objects like request, session, application etc.
 There are many implicit objects, operators and reserve words in EL.It is the newly added
feature in JSP technology version 2.0.
 Types of expression languages are
1. Immediate evaluation:- in this all the expressions are immediately evaluated . this
can only be used within the template text or as the value of a jsp element attribute
that can accept runtime expressions.
Syntax for Expression Language (EL)
${< expression >}
 2. Deffered evaluation :- this can evaluated at specific phases in jsf life cycle as defined
by whatever technology is using the expression .
syntax :- #{< expression >}

Operators available in EL
Arithmetic Operators
 + : Addition
 -[binary] : Subtraction
 * : Multiplication
 / or div : Division
 % or mod : Modulo [Remainder]
 -[unary] : Negation of a value
Logical Operators
 && or and : Test for logical AND
 || or or : Test for logical OR
 ! or not : Unary Boolean complement
Relational Operators
 == or eq : Test for equality
 != or ne: Test for inequality
 < or lt : Test for less than
 > or gt : Test for greater than
 <= or le : Test for less than or equal
 >= or ge : Test for greater than or equal
Conditional Operators
The following is the syntax for conditional operators:
 Condition ? If True : If False
The empty Operator
 The empty operator is a prefix operation that can be used to determine if a value is null or
empty
The .[A Dot] Operator
 The .[a dot] operator is shorthand for calling a Javabeans property accessor for the property
whose name is on the right side of the operator.
 If the object being accessed is Map, the .[a dot] operator uses the name of the right side as a
string literal and uses it as key to fetch the result.
 Example:- ${header.host} <%-- Evaluates to localhost:8080 --%>
The [] Operator
 The [] operator is polymorphic indexing, which can be used for indexing collections including
Maps, Lists, Arrays.
 The value inside the brackets is used as a key into a map or a list or array index.
 Example:- ${colors[5]} <%-- Evaluates to violet --%>

EL in JSP
https://www.youtube.com/watch?v=KmREMEhj5eE
Significance of using JSTL. And its disadvantages
JSTL is the JSP Standard Tag Library. The JSTL came about under JSR-52 of the Java Community
Process (JCP).
 JSR-52 covers the creation of a standard tag library for JavaServer Pages and allows this
library to be available to all compliant JSP containers.
 These tag libraries provide a wide range of custom action functionality that most JSP authors
have found themselves in need of in the past.
 Having a defined specification for how the functionality is implemented means that a page
author can learn these custom actions once and then use and reuse them on all future
products on all application containers that support the specification.
 Using the JSTL will not only make your JSPs more readable and maintainable, but will allow
you to concentrate on good design and implementation practices in your pages.
 The JSTL encapsulates common functionality that a typical JSP author would encounter.
 This set of common functionality has come about through the input of the various members
of the expert group. Since this expert group has a good cross section of JSP authors and
users, the actions provided in the JSTL should suit a wide audience.
 The JSTL is a set of custom actions that is based on the JSP 1.2 and Servlet 2.3 specifications.
While the JSTL is commonly referred to as a single tag library, it is actually composed of four
separate tag libraries:
o Core
o XML manipulation
o SQL
o Internationalization and formatting

Disadvantages of JSTL
 JSTL puts the processing burden to the server. Java Scriplets and the tag libraries both are
compiled into a servlet which is then executed by the servlet engine. Java code embedded in
scriplets is pretty much just copied into the servlet , but on the other hand JSTL tags causes
much morecode to be added to the servlet .
 Scriplets are more powerful than JSTL tags if anyting has to be done in the JSP pages then
the developer might want to stick to the embedded java code. JSTL provides a powerful set
of reusable libraries to the application developer. However JSTL cannot do everything that
the java code can do .

JSTL Fixes JSP Scriplet’s Shortcomings.


1] As JSTL tags are XML based tags,they cleanly and consistently blend into a page’s HTML markup
tags.
2] JSTL tags are easier to use effectively as they do not require any knowledge of programming or
Java.This is very useful for the non-programmers or the inexperience.
3] JSTL tags encapsulate reusable application logic much like the formatting of dates and numbers
.Using JSP Scriplets,the same code spec would have to be repeated everywhere it is required or it
would need to be moved into Java helper classes.
4] JSTL tags can reference objects in Request and Session objects without knowing the object’s type
with no typecasting required.
5] JSP EL[Expression Language]makes it easy to call the getter and the setter methods on Java
objects.JSTL makes extensive use of the EL expression.
Core Tags
https://www.youtube.com/watch?v=R0EnI9_ZMA0

Conditional Action Tag Libraries


The content deliverd by JSP based applications is often dynamic in nature. It’s generated content
begin dependent on the values of ever-changig application data. The conditional tags provided by
the JSTL core tag library are far better suited for this purpose.
Conditional actions are used for conditional processing within a JSP page.
Action Elements Descriptions
<c:if> Evaluates a test expression and then processes its body
content only if that expression evaluates to true.
<c:choose> Provides mutually exclusive cconditions.
<c:when> Represents an alternative within a <c:choose> element.
<c:otherwise> Represents the last alternative within a<c:choose> element.

Example:
<c:chooose>
<c:when test=”${book.name == ‘Oracle 11g for Professionals’}”>
<FONT COLOR=”Black”>
</c:when>
<c:when test=”${book.name == ‘struts 2.0 for Beginners’}>
<FONT COLOR=”Blue”>
</c:when>
<c:when test=”${book.name == ‘Hibernate 3 for Beginners’}>
<FONT COLOR=”Brown”>
</c:when>
<c:otherwise>
<FONT COLOR=”White”>
</c:otherwise>
</c:choose>

Core tag Libraies using sutaible example.


The core tag library contains tags that are essential to nearly any web application.Examples of core
tag libraries are looping, evaluating of expression and basic input and output.
The URI of the core tag library is http://xmlns.jcp.org/jsp/jstl/core and The core area comprise four
distinct functional sections
Function Tag Description
Variable Support Remove set The set tag sets the value of an EL variable or the
property of an EL variable in any of the JSP scopes
(page, request, session, or application). If the variable
does not already exist, it is created
Flow Control choose To execute flow control logic, a page author must
when generally resort to using scriptlets.
otherwise
forEach
forTokens
if
URL Management import The jsp:include element provides for the inclusion of
param static and dynamic resources in the same context as the
redirect current page. However, jsp:include cannot access
param resources that reside outside the web application, and it
url causes unnecessary buffering when the resource
param included is used by another element.

Miscellaneous catch The catch tag provides a complement to the JSP error
out page mechanism. It allows page authors to recover
gracefully from error conditions that they can control.
Actions that are of central importance to a page
should not be encapsulated in a catch; in this way their
exceptions will propagate instead to an error page.
Actions with secondary importance to the page should
be wrapped in a catchso that they never cause the error
page mechanism to be invoked.

SQL Tag Libraries


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.
 The SQL tag library allows the tag to interact with RDBMSs (Relational Databases) such as
Microsoft SQL Server, mySQL, or Oracle.
 Syntax:- <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
 The JSTL Database / SQL tag library allows performing database queries, access query results
and perform Inserts, Updates and Deletes.

 Example:-
<%@ page import = "java.io.*,java.util.*,java.sql.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c"%>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/sql" prefix = "sql"%>
<html>
<head>
<title>JSTL sql:query Tag</title>
</head>
<body>
<sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost/TEST"
user = "root" password = "pass123"/>
<sql:query dataSource = "${snapshot}" var = "result">
SELECT * from Employees;
</sql:query>
<table border = "1" width = "100%">
<tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>

<c:forEach var = "row" items = "${result.rows}">


<tr>
<td> <c:out value = "${row.id}"/></td>
<td> <c:out value = "${row.first}"/></td>
<td> <c:out value = "${row.last}"/></td>
<td> <c:out value = "${row.age}"/></td>
</tr>
</html>
</c:forEach>
</table>
</body>
</html>
Question:
1. Why to use Java Server Pages?
2. Write the disadvantages Of JSP.
3. Distinguish between JSP and Servlets.
4. Describe the Life Cycle of a JSP Page.
5. How webserver handles JSP request?
6. Explain with example Page Directive with its attributes.
7. Explain all the Directives with syntax in JSP Pages and JSP Documents.
8. Write a short note on JSP Elements.
9. Write a JSP file to get a feedback from index file (name, message) which also accepts header
from another file.
10. Write a JSP file to get a feedback from index file (name, message) which also accepts header
from another file using JSP document.
11. Explain the following Action Commands with suitable example:
1. <jsp:forward> 2. <jsp:include> 3. <jsp:param>
12. Write a short note on Javabean tags.
13. Explain all Implicit Objects.
14. Explain Character Quoting Conventions with a suitable example.
15. What are the type of Unified Expression Language [Unified El] explain all in detail.
16. What are the types of Expressions explain with code snippet.
17. List all the Operators available in EL explain any two of them.
18. Explain the Dot . , [ ] and empty operator
19. Write the significance of using JSTL. Also write its disadvantages.
20. Explain Conditional Actions Tag Libraries using suitable example.
21. Explain Iterator Actions Tag Libraries using suitable example.

You might also like