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

Unit 3 Je

sedtrwae qe qerf qarg r
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)
21 views24 pages

Unit 3 Je

sedtrwae qe qerf qarg r
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

1 How JSP functions and Executes?

(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

● How does a JSP function


Jsp code spec can be broken into two categories:
● Elements that are processed by the JSP engine on the Web server
● Template data or everything other than such elements, that the JSP engine
ignores
● JSP rage is executed by a Web server that either has a built in JSP engine or
accesses a third party JSP engine, which it is configured to use. When a client
asks for a JSP resource the web server fields that request and delivers it to the
JSP engine along with a RESPONSE object.
● Jsp engine uses the jsp code spec referenced by the client to process the client
response obtain whatever is required from associated resources.
● Jsp uses HttpServletRequest and HttpServletResonse for the http protocol
similar to hat of servlet.● Most jsp is pain html interspersed with special JSP tags
● The scriplet tag encloses java code, which accept and processes the
parameters from html form using request object and send response to client
using response object. *****● How does a JSP Execute?
● first browser send request to server via http get or post method.
● New jsp is translated into java class by the jsp engine, which is child of the
web server, by having its embeded java code compiled into a servlet.
● When servlet is run by the jvm its init() is called first.
● Then individual request are sent to the servlet service() where their response
is assembled.
2 Explain Life Cycle of a JSP Page. (NOV 2022)
Explain JSP life cycle with proper diagram. (APR 2023)
● Life cycle of JSP
A Java Server Page life cycle is defined as the process started with its
creation which later translated to a servlet and afterward servlet
lifecycle comes into play. This is how the process goes on until its
destruction.

Following steps are involved in JSP life cycle:


● Translation of JSP page to Servlet
● Compilation of JSP page(Compilation of JSP into test.java)
● Classloading (test.java to test.class)
● Instantiation(Object of the generated Servlet is created)
● Initialization(jspInit() method is invoked by the container)
● Request processing(_jspService()is invoked by the container)
● JSP Cleanup (jspDestroy() method is invoked by the container)
● Translation of JSP page to Servlet :
o This is the first step of JSP life cycle. This translation phase deals
with Syntactic correctness of JSP. Here test.jsp file is transllated to
test.java.

● Compilation of JSP page :


o Here the generated java servlet file (test.java) is compiled to a class
file (test.class).

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

● buffer <%@ page buffer = "8kb" %>


▪ Specifies a buffering model for the output stream.
● autoFlush <%@ page autoFlush = "true" %>
▪ Controls the behavior of the servlet output buffer.
● contentType <%@ page contentType = "text/xml" %>
▪ Defines the character encoding scheme.
● errorPage <%@ page errorPage = "MyErrorPage.jsp" %>
▪ Defines the URL of another JSP that reports on Java unchecked
runtime exceptions.
● isErrorPage <%@ page isErrorPage = "true" %>
▪ Indicates if this JSP page is a URL specified by another JSP page's
errorPage attribute.
● extends <%@ page extends = "somePackage.SomeClass" %>
▪ Specifies a superclass that the generated servlet must extend.

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

Syntax: [In a regular JSP page]


● <%@ taglib uri='<TaglibraryURI>" prefix="<TagPrefix>" %>
Syntax: [In an XML based JSP page]
● <jsp:directive.taglib uri="<TaglibraryURI>" prefix="<TagPrefix>" />

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.

Syntax: [In a regular JSP page]


<%@ include file = "relative url" >
4 Explain the various scope of JSP application. (NOV 2018)
● The scope attribute has four possible values: (a) page, (b)request, (c)session, and (d)
application.
● Page scope is managed by the pageContext object. As a page context object is created for
every JSP page, so, every JSP page will have a specific page scope. PageScope is the default
scope. The object is accessible only from within the JSP page where it had been created. A
page-scope object is stored within the implicit pageContext object. The page scope ends when
the page stops executing. If we declare the info in page scope by using pageContext object
then that data should have the scope up to this JSP page. Note that when the user refreshes
the page while executing a JSP page, new instances will be created of all page-scope object.
o Request scope is managed by the request object. This object is used for reading the request
object. If the same request is shared by more than one JSP page those sharing the same
request object come under the same request scope. Request Scope begins whenever the
request object is created by the servlet container and the request scope ends whenever the
request object is deleted by the servlet container. As the request object is stored in the
pageContext object we can manage request scope attributes by using the pageContext
object. The object is accessible from any JSP page servicing an equivalent HTTP request that’s
serviced by the JSP page that created the thing AAA request-scope object is stored in the
implicit request object. The request scope ends at the conclusion of the HTTP request. If we
declare the info in the request object then that data should have the scope up to the number
of resources that are visited by this request object.
o Session scope is managed by the session object. The same session object is available to all
JSP pages as long as the session is not expired. Whenever a session is expired or
session.invalidate() is called then a new session is created for the next requesting page. This
object is used for reading attributes from HTTPSession. The object is accessible from any JSP
page that’s sharing an equivalent HTTP session because of the JSP page that created the
thing. A session-scope object is stored within the implicit session object. The session scope
ends when the HTTP session times out or is invalidated. If we declare the info in HTTPSession
object then that data should have the scope up to the number of resources that are visited
by this client.
o The application scope is maintained by the application pointing object. Application scope
begins whenever the ServletContext implementation object is created. Application scope
ends whenever the ServletContext implementation object is deleted. This object is used for
reading attributes from ServletContext. The object is accessible from any JSP page that’s
utilized in an equivalent Web application because the JSP page that created the thing, within
any single Java virtual machine. The concept is analogous thereto of a Java static variable.
An application-scope object is stored within the implicit application servlet context object.
The application scope ends when the appliance itself terminates, or when the JSP container
or servlet container shuts down. If we declare the info in the ServletContext object then that
data should have the scope up to the number of resources that are available within the
present web application.
5 Explain the implicit objects of JSP. (NOV 2018)
List the name of JSP implicit objects. Explain any three in detail. (APR 2023)
Implicit Objects
● Delivering dynamic website content to a client browser requires interacting
with Java objects on the Web server. Java scripting elements provide a great
deal of power and flexibility to the developer to] achieve this. In addition to
permitting such intercommunication the JSP engine exposes a number of
internal Java objects to the developer. These objects do not need to be declared
or instantiated by the developer, but are provided by the JSP engine in its
implementation and execution.
● Scripting elements can access predefined variables assigned by the JSP engine
and using their content reference implicit objects to access request and
application data. These objects are instances of classes defined by the Servlet
and JSP specifications.
● All such implicit objects are available only to scriptlets or expressions. They
are not available in declarations. Declarations translate into class variables or
method declarations. Implicit Ejects are only available in _jspService() of the
generated Servlet.
Following table lists out the nine Implicit Objects that JSP supports
The request Object
● The request object is an instance of a javax.servlet.http.HttpServletRequest
object. Each time a client requests a page the JSP engine creates a new object to
represent that request.
● The request object provides methods to get the HTTP header information
including form data, cookies, HTTP methods etc
The response Object
The response object is an instance of a javax.servlet.http.HttpServletResponse
object. Just as the server creates the request object, it also creates an object to
represent the response to the client. The response object also defines the
interfaces that deal with creating new HTTP headers. Through this object the JSP
programmer can add new cookies or date stamps, HTTP status codes, etc.
The out Object
● The out implicit object is an instance of a javax.servlet.jsp.JspWriter object
and is used to send content in a response.
● The initial JspWriter object is instantiated differently depending on whether
the page is buffered or not. Buffering can be easily turned off by using the
buffered = 'false' attribute of the page directive.
● The JspWriter object contains most of the same methods as the
java.io.PrintWriter class. However,JspWriter has some additional methods
designed to deal with buffering. Unlike the PrintWriter object, JspWriter throws
IOExceptions.
Following table lists out the important methods that we will use to write
boolean char, int, double, object, String, etc.

The session Object


● The session object is an instance of javax.servlet.http.HttpSession and behaves
exactly the same waythat session objects behave under Java Servlets.
● The session object is used to track client session between client requests.
● The application Object
● The application object is direct wrapper around the ServletContext object
6 How to set and access the properties of java bean in JSP? (APR 2019)
Explain the <jsp:useBean > tag with its attribute. Support your answer with suitable code
Give an explanation of the jsp:useBean action tag's attributes and usage. (NOV 2022)
Define following action elements in JSP with suitable code example. (APR 2023)
a. Jsp:include b. Jsp:forward c. Jsp:param d. Jsp:setProperty e. Jsp:getProperty
Loading a Javabean
The <jsp:useBean> Action
The useBean action is quite versatile. It first searches for an existing object utilizing the id
and scope variables. If an object is not found, it then tries to create the specified object.
The simplest way to load a bean is as follows −
<jsp:useBean id = "name" class = "package.class" />
Once a bean class is loaded, you can use jsp:setProperty and jsp:getProperty actions to
modify and retrieve the bean properties.
Following table lists out the attributes associated with the useBean action −

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 −

The <jsp:getProperty> Action


The getProperty action is used to retrieve the value of a given property and
converts it to a string, and finally inserts it into the output. The getProperty
action has only two attributes, both of which are required. The syntax of
the getProperty action is as follows – <jsp:useBean id = "myName" ... />
<jsp:getProperty name = "myName" property = "someProperty" .../>

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 −

Following is the content of the hello.jsp file –


<p>Today's date: <%= request.getParameter(“username”) %></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:forward page =
"date.jsp" >
**<jsp:param name=”username”
value=”siddhesh”/>**</jsp:forward>**</center>
</body>**</html>
● Including other Files
The <jsp:include> Action
● This action lets you insert files into the page being generated. The syntax looks
like this −
● <jsp:include page = "relative URL" flush = "true" />
● Unlike the include directive, which inserts the file at the time the JSP page is
translated into
a servlet, this action inserts the file at the time the page is requested.
Following table lists out the attributes associated with the include 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

9 Explain JSTL core Tag Library. (NOV 2018)


JSTL Core Tags
The JSTL core tag provides variable support, URL management, flow
control etc. The syntax used for including JSTL core library in your JSP
is: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
14 What exactly is JSTL? Describe XPath in detail. (NOV 2022)

JSP tags were logical evolutionary steps towards creating fast,


maintainable, Java based, Internet delivered, applications. In mid 2002
the release of the JSP Standard Tag Library [JSTL] represented a really
huge step that speeded up yet simplified the Java based application
development process.

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.

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

● 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

● XPath (XML Path Language) ** XPath (XML Path Language) is


an expression language designed to support the query or
transformation of XML documents.**It was defined by the
World Wide Web Consortium (W3C) and can be used to
compute values (e.g., strings, numbers, or Boolean values)
from the content of an XML document.** Support for XPath
exists in applications that support XML, such as web browsers,
and many programming languages.

You might also like