Unit 3 Je
Unit 3 Je
(APR 2019)
Explain the reasons to use JSP. (NOV 2019) Java Server Pages? Java Server
Pages?
● JavaServer Pages (JSP) is a technology for developing Webpages that supports dynamic
content. This helps developers insert java code in HTML pages by making use of special JSP
tags, most of which start with <% and end with %>
● A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a
user interface for a Java web application. Web developers write JSPs as text files that combine
HTML or XHTML code, XML elements, and embedded JSP actions and commands.
● Using JSP, you can collect input from users through Webpage forms, present records from a
database or another source, and create Webpages dynamically.
● JSP tags can be used for a variety of purposes, such as retrieving information from a
database or registering user preferences, accessing JavaBeans components, passing control
between pages, and sharing information between requests, pages etc.
● JavaServer Pages often serve the same purpose as programs implemented using the
Common
Gateway Interface (CGI). But JSP offers several advantages in comparison with the CGI.
● Performance is significantly better because JSP allows embedding Dynamic Elements in
HTML
Pages itself instead of having separate CGI files.
● JSP are always compiled before they are processed by the server unlike CGI/Perl which
requires the server to load an interpreter and the target script each time the page is
requested.
● JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has
access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP, etc.
● JSP pages can be used in combination with servlets that handle the business logic, the
model
supported by Java servlet template engines. ● No body can borrow the code (code remains
on web server) ● Faster loading of web pages ● No browser compatibility issue
● Disadvantages of JSP
o As JSP pages are translated to servlets and compiled, it is difficult to trace
errors occurred in
JSP pages.
o JSP pages require double the disk space to hold the JSP page. (Because JSP
pages are
translated into class files, the server has to store the resultant class files with the
JSP pages)
o JSP pages require more time when accessed for the first time as they are to be
compiled on the server.
o Simple task are hard to code.
o Difficult in looping in tags many times nesting of brackets make things
complex. ****● JSP v\s Servlets
● Classloading :
o Servlet class which has been loaded from JSP source is now loaded
into container.
● Instantiation :
o Here instance of the class is generated. The container manages one
or more
instance by providing response to requests.
● Initialization :
o jspInit() method is called only once during the life cycle immediately
after the
generation of Servlet instance from JSP.
● Request processing :
o _jspService() method is used to serve the raised requests by JSP.It
takes request and
response object as parameters.This method cannot be overridden.
● JSP Cleanup :
o In order to remove the JSP from use by the container or to destroy
method for servlets jspDestroy()method is used. This method is called
once, if you need to perform any cleanup task like closing open files,
releasing database connections jspDestroy() can be overridden.
3 What are directives in JSP? Explain page directive in detail. (With all
its attributes)
What are directives in JSP? Explain its types. (NOV 2022)
What are JSP directives? Explain different types of directives with
example. (APR 2023)
page directive
The page directive is used to provide instructions to the container.
These instructions pertain
to the current JSP page. You may code page directives anywhere in
your JSP page. By convention, page directives are coded at the top of
the JSP page.
Syntax: [In a regular JSP page]
● <%@ page attributes=” <Value>” %>
Syntax: [In an XML based JSP page]
● <jsp:directive.page attributes="<Value>" />
▪ Specifies a list of packages or classes for use in the JSP as the Java
import statement does for Java classes.
● session <%@ page session = "true" %>
▪ Specifies whether or not the JSP page participates in HTTP sessions.
Taglib directive
The JavaServer Pages API allow you to define custom JSP tags that
look like HTML or XML tags and a tag library is a set of user-defined
tags that implement custom behavior. The taglib directive declares
that your JSP page uses a set of custom tags, identifies the location of
the library, and provides means for identifying the custom tags in your
JSP page.
include Directive
The include directive is used to include a file during the translation
phase. This directive tells
the container to merge the content of other external files with the
current JSP during the
translation phase. You may code the include directives anywhere in
your JSP page.
Let us now discuss the jsp:setProperty and the jsp:getProperty actions before
giving a valid
example related to these actions.
The <jsp:setProperty> Action
The setProperty action sets the properties of a Bean. The Bean must have been
previously defined before this action. There are two basic ways to use the
setProperty action − You can use jsp:setProperty after, but outside of a
jsp:useBean element, as given below −
<jsp:useBean id = "myName" ... />
<jsp:setProperty name = "myName" property = "someProperty" .../>
In this case, the jsp:setProperty is executed regardless of whether a new bean
was instantiated or an existing bean was found.
A second context in which jsp:setProperty can appear is inside the body of
a jsp:useBean element, as given below −
<jsp:useBean id = "myName" ... >
<jsp:setProperty name = "myName" property = "someProperty" .../>
</jsp:useBean>
Here, the jsp:setProperty is executed only if a new object was instantiated, not if
an existing one was found.
Following table lists out the attributes associated with the setProperty action −
Following table lists out the required attributes associated with the getProperty
action – The forward action terminates the action of the current page and
forwards the request to another resource such as a static page, another JSP
page, or a Java Servlet. Following is the syntax of the forward action −
<jsp:forward page = "Relative URL" />
Following table lists out the required attributes associated with the forward
action −
Example
Let us define the following two files (a)date.jsp and (b) main.jsp as follows −
Following is the content of the date.jsp file –
<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>
Following is the content of the main.jsp file −
<html>
<head>
<title>The include Action Example</title>
</head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:include page = "date.jsp" flush = "true" />
</center>
</body>
</html>
7. What is EL? Explain immediate EL, deferred EL, LValue and RValue in detail.
(NOV 2018)
Write short note on Restriction, Projection and Partitioning Operators in EL.
(APR 2019)
Unified Expression Language, Expression Language
The expression language introduced in JSP 2.0 allows page authors to use simple
expressions to dynamically read data from JavaBeans components. For example,
the test attribute of the following conditional tag is supplied with an EL
expression that compares the number of items in the session- scoped bean
named cart with 0.
<c:if test="${sessionScope.cart.numberOfItems > 0}"> *******</c:if>
unified expression language allows page authors to use simple expressions to
perform the following tasks:
● Dynamically read application data stored in JavaBeans components, various
data structures, and implicit objects ● Dynamically write data, such as user input
into forms, to JavaBeans components ● Invoke arbitrary static and public
methods ● Dynamically perform arithmetic operations
Immediate evaluation
● Immediate evaluation means that the JSP engine evaluates the expression and
returns the result immediately when the page is first rendered.
● Those expressions that are evaluated immediately use the ${} syntax
● ${9+10}
Deferred evaluation
● Deferred evaluation means that the technology using the expression language
can employ its own machinery to evaluate the expression sometime later during
the page’s life cycle, whenever it is appropriate to do so.
● Expressions whose evaluation is deferred use the #{}
● <h:inputText id="name" value="#{customer.name}" />
Value and Method Expressions
● The unified EL defines two kinds of expressions: value expressions and method
expressions. Value expressions can either yield a value or set a value. Method
expressions reference methods that can be invoked and can return a value.
● Value Expressions
o Value expressions can be further categorized into rvalue and lvalue
expressions. o Rvalue expressions are those that can read data, but cannot write
it. o Lvalue expressions can both read and write data.
o All expressions that are evaluated immediately use the ${} delimiters and are
always rvalue expressions. Expressions whose evaluation can be deferred use
the #{}delimiters and can act as both rvalue and lvalue expressions. Consider
these
two value expressions:
o <taglib:tag value="${customer.name}" /> ****o <taglib:tag
value="#{customer.name}" />
Referencing Objects
● A top-level identifier (such as customer in the expression customer.name) can
refer to the following objects: o Lambda parameters o EL variables o Managed
beans o Implicit objects o Classes of static fields and methods
An enum constant is a special case of a static field, and you can reference such a
constant directly. For example, consider this enum class:
public enum Suit {hearts, spades, diamonds, clubs}
In the following expression, in which mySuit is an instance of Suit, you can
compare suit.hearts to the instance: ${mySuit == suit.hearts}
Referencing Object Properties or Collection Elements
o To refer to properties of a bean, static fields or methods of a class, or items of
a collection, you use the. or [] notation. The same syntax can be used for
attributes of an implicit object, because attributes are placed in a map.
o To reference the name property of the customer bean, use either the
expression o ${customer.name} or the expression ${customer["name"]}.
o ${customer.address["street"]} Referencing Literals
o The EL defines the following literals: o Boolean: true and false
o Integer: As in Java o Floating-point: As in Java
o String: With single and double quotes; " is escaped as \", ' is escaped as \', and
\is escaped as \\ o Null: null
Parameterized Method Calls
The EL offers support for parameterized method calls.
Both the . and [] operators can be used for invoking method calls with
parameters, as shown in the following expression syntax: o expr-a[expr-
b](parameters) o expr-a.identifier-b(parameters)
<h:inputText value="#{userNumberBean.userNumber('5')}">
Lambda Expressions
o A lambda expression is a value expression with parameters. The syntax is
similar to that of the lambda expression in the Java programming language,
except that in the EL, the body of the lambda expression is an EL expression.
o A lambda expression uses the arrow token (->) operator. The identifiers to the
left of the operator are called lambda parameters. The body, to the right of the
operator, must be an EL expression. The lambda parameters are enclosed in
parentheses; the parentheses can be omitted if there is only one parameter.
Here are some examples:
o (p1, p2) -> System.out.println("Multiple parameters: " + p1 + ", " + p2);
Operations on Collection Objects
● The EL supports operations on collection objects: sets, lists, and maps. It
allows the dynamic creation of collection objects, which can then be operated
on using streams and pipelines.
0● For example, you can construct a set as follows:
o {1,2,3}
● You can construct a list as follows; a list can contain various types of items:
o [1,2,3]
o [1, "two", [three,four]]
● You can construct a map by using a colon to define the entries, as follows:
o {"one":1, "two":2, "three":3}
● You operate on collection objects using method calls to the stream of
elements derived from the collection. Some operations return another stream,
which allows additional operations. Therefore, you can chain these operations
together in a pipeline.
● A stream pipeline consists of the following:
o A source (the Stream object)
o Any number of intermediate operations that return a stream (for example,
filter and map)
o A terminal operation that does not return a stream (for example, toList())
● The stream method obtains a Stream from a java.util.Collection or a Java
array. The stream operations do not modify the original collection object. For
example, you might generate a
list of titles of history books as follows:
o books.stream().filter(b->b.category == 'history')
o .map(b->b.title)
o .toList()
● The following simpler example returns a sorted version of the original list:
o [1,3,5,2].stream().sorted().toList()
● The following subset of operations is supported by the EL
Explain the advantages of JSTL over JSP. (NOV 2018)
● What Is Wrong In Using JSP Scriptlet Tags.
● The java code embedded within the scriptlet looks ugly and
obtrusive
● The developer who does not know Java actually modify the
embedded java code Thus, this disadvantage nullifies the major
benefit of JSP, which is designers and business people to update page
content.
● The Java code embedded within the Scriptlets cannot be re-used by
another jsp pages. So the common logic code spec ends up being re-
implemented in multiple jsp pages
● Retrieving objects out of the HTTP request and sessions is not
manageable. they have to be specifically typecast to the object's class.
This requires that the object class be known to the JSP by importing or
fully qualifying the class name
● How jstl fixes jsp scriptlets shortcommings.
● jstl tags are XML based tags, they cleanly and consistently blend into
a pages HTML markup tags
● Easy to call getter and setter
● No type casting require in request and response object
● 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
programming or the Inexperience
JSTL allows programming JSP pages using tags, rather than the
scriptlets that most JSP developers are already comfortable with. JSTL
does nearly everything that the regular scriptlet does. JSTL was
introduced to allow the JSP developers to create Web applications
Using tags rather than the Java code.
● Tag libraries
● JSTL includes a wide variety of tags that fit into discrete
functional areas. To reflect this, as well as to give each area its
own namespace, JSTL is exposed as multiple tag libraries. The
URIs for the libraries are as follows:
o Core: http://java.sun.com/jsp/jstl/core
o XML: http://java.sun.com/jsp/jstl/xml
o Internationalization: http://java.sun.com/jsp/jstl/fmt
o SQL: http://java.sun.com/jsp/jstl/sql
o Functions: http://java.sun.com/jsp/jstl/functions