EJ Unit 3
EJ Unit 3
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
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 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.
The page directive defines attributes that apply to an entire JSP page.
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>
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>
Action Commands
3.1 .<jsp:forward>
3.2. <jsp:include>
3.3 <jsp:param>
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("user",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>
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 .
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>
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.
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>