Enterprise Java Unit 3
Enterprise Java Unit 3
3
Q.1 What are the benefits of using JSP?/ Explain the reason why use JSP?
A JSP life cycle is defined as the process from its creation till the destruction. This is
similar to a servlet life cycle with an additional step which is required to compile a JSP
into servlet. When the browser asks for a JSP, JSP engine first checks whether it needs to
compile the page. If the JSP is last compiled or the recent modification is done in JSP,
then the JSP engine compiles the page.
JSP Lifecycle follows the following steps:
1. Translation of JSP page
2. Compilation of JSP page(Compilation of JSP page into _jsp.java)
3. Classloading (_jsp.java is converted to class file _jsp.class)
4. Instantiation(Object of generated servlet is created)
5. Initialisation(_jspinit() method is invoked by container)
6. Request Processing(_jspservice() method is invoked by the container)
7. Destroy (_jspDestroy() method invoked by the container)
1. Translation of the JSP Page:
A Java servlet file is generated from a JSP source file. This is the first step of JSP
life cycle. In translation phase, container validates the syntactic correctness of JSP
page and tag files.
The JSP container interprets the standard directives and actions, and the
custom actions referencing tag libraries used in this JSP page.
When the conversion happens all template text is converted to println()
statements and all JSP elements are converted to Java code.
2. Compilation of the JSP Page:
The generated java servlet file is compiled into java servlet class
The translation of java source page to its implementation class can happen at any
time between the deployment of JSP page into the container and processing of the
JSP page.
Java servlet is compiled to a class file.
3. Class loading:
Servlet class that has been loaded from JSP source is now loaded into the container
4. Instantiation:
In this step the object i.e. the instance of the class is generated.
The container manages one or more instances of this class in the response to
requests and other events. Typically, a JSP container is built using a servlet
container. A JSP container is an extension of servlet container as both the container
support JSP and servlet.
A JSP Page interface which is provided by container provides init() and destroy ()
methods.
There is an interface HttpJSPPage which serves HTTP requests, and it also contains
the service method.
5. Initialization:
public void jspInit()
{
//initializing the code
}
jspinit() method will initiate the servlet instance which was generated from JSP and
will be invoked by the container in this phase.
Once the instance gets created, init method will be invoked immediately after that
It is only called once during a JSP life cycle, the method for initialization is
declared as shown above
6. Request processing:
void _jspservice
(HttpServletRequest request HttpServletResponse response) { //handling all request
and
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT
3
responses }
_jspservice() method is invoked by the container for all the requests raised by
the JSP page during its life cycle
For this phase, it has to go through all the above phases and then only service
method can be invoked.
It passes request and response objects
This method cannot be overridden
The method is shown above: It is responsible for generating of all HTTP
methods i.eGET, POST, etc.
7. Destroy:
public void _jspdestroy()
{
//all clean up code
}
_jspdestroy() method is also invoked by the container
This method is called when container decides it no longer needs the servlet
instance to service requests.
When the call to destroy method is made then, the servlet is ready for a garbage
collection
This is the end of the life cycle.
We can override jspdestroy() method when we perform any clean up such
as releasing database connections or closing open files.
i. JSP directives serve special processing information about the page to the JSP Server.
ii. A JSP directive affects the overall structure of the servlet class.
iii. They do not produce any output that is visible to the client.
iv. It usually has the following form:
<%@ directive attribute = "value" %>
v. Directives can have a number of attributes which you can list down as key-
value pairs and separated by commas.
vi. The blanks between the @ symbol and the directive name, and between the last
attribute and the closing %>, are optional.
vii. There are three types of directive tag:
Sr Directive &
no Description
.
1. <%@ page ... %>
Defines page-dependent attributes, such as scripting language,
error page, and buffering requirements.
2. <%@ include ... %>
Includes a file during the translation phase.
3. <%@ taglib ... %>
Declares a tag library, containing custom actions, used in the page
Objec Typ
t e
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
1. Out:
An out object is an implicit object for writing data to the buffer and sending output as
a response to the client's browser.
For servlet, we need to write:
PrintWriter
out=response.getWriter(); But
in JSP, we need to write:
<% out.print("JspWriter”); %>
2. Request:
The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp
request by the web container.
It can be used to get request information such as parameter, header information, remote
address, server name, server port, content type, character encoding etc.
It can also be used to set, get and remove attributes from the jsp
request scope. Syntax:
<%String name=request.getParameter("uname");%>
3. response:
In JSP, response is an implicit object of type HttpServletResponse.
The instance of HttpServletResponse is created by the web container for each jsp
request. It can be used to add or manipulate response such as redirect response to
another resource, send error etc. Syntax:
<%response.sendRedirect("http://www.google.com");%>
4. config:
In JSP, config is an implicit object of type ServletConfig.
This object can be used to get initialization parameter for a particular
JSP page. The config object is created by the web container for each
jsp page.
Generally, it is used to get initialization parameter from the web.xml file.
A config object is a configuration object of a servlet that is mainly used to access and
receive configuration information such as servlet context, servlet name, configuration
parameters, etc. It
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT
3
uses various methods used to fetch configuration
information. Syntax:
<%String driver=config.getInitParameter("dname");%>
5. application:
In JSP, application is an implicit object of type ServletContext.
The instance of ServletContext is created only once by the web container when
application or project is deployed on the server.
This object can be used to get initialization parameter from configuaration
file (web.xml). It can also be used to get, set or remove attribute from the
application scope.
Syntax:
<%String driver=application.getInitParameter("dname");%>
6. session:
In JSP, session is an implicit object of type HttpSession.
The Java developer can use this object to set, get or remove attribute or to get session
information. Syntax:
<%String name=(String)session.getAttribute("user"); %>
7. pageContext:
In JSP, pageContext is an implicit object of type PageContext class.
The pageContext object can be used to set, get or remove attribute from one of the
following scopes:
page request session
application. In JSP, page scope is
the default scope. Syntax:
%<String name=(String)pageContext.getAttribute("user",PageContext.SESSI
ON_SCOPE);%>
8. page:
In JSP, page is an implicit object of type Object class.
This object is assigned to the reference of auto generated
servlet class. It is written as: Object page=this;
For using this object it must be cast to Servlet type.
For example: <% (HttpServlet)page.log("message"); %>
Since, it is of type Object it is less used because you can use this object
directly in jsp. For example:
<% this.log("message"); %>
9. exception:
In JSP, exception is an implicit object of type
java.lang.Throwable class. This object can be used to print the
exception.
But it can only be used in error
pages. Syntax:
<%= exception %>
1. Large complex JSP pages make use of JSTL tag libraries which exceeds class size
limitation. Because size of java class is limited.
2. JSTL is not so flexible and not as extensive as JSP Scriptlet. The JSTL is not nearly as
evolved as Java itself.
3. It is easier to programmer who knows HTML skill set. If JSTL get translated into Java
code, experienced programmer may wonder why he does not do that himself and save
the time. So it may difficult to carry out for experienced programmers.
4. JSP files that make use of JSTL will generate a great deal of overhead code.
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT
3
Q. 7 How JSP functions and Executes?
Functions of JSP:
The web server needs a JSP engine, ie, a container to process JSP pages. The JSP
container is responsible for intercepting requests for JSP pages.
A JSP container works with the Web server to provide the runtime environment and other
services a JSP needs. It knows how to understand the special elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web application.
The following steps explain how the web server creates the Webpage using JSP:
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it
to a JSP engine. This is done by using the URL or JSP page which ends with jsp instead of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet content. This
conversion is very simple in which all template text is converted to println() statements
and all JSP elements are converted to Java code. This code implements the
corresponding dynamic behaviour of the page.
The JSP engine compiles the servlet into an executable class and forwards the original
request to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and
executes it. During execution, the servlet produces an output in HTML format. The
output is furthur passed on to the web server by the servlet engine inside an HTTP
response.
The web server forwards the HTTP response to your browser in terms of static HTML
content. Finally, the web browser handles the dynamically-generated HTML page
inside the HTTP response exactly as if it were a static page.
In <JSP:setProperty> action the name attribute tells the bean whose property will be set. The
Bean must have been previously defined. The property attribute indicates the property that
we want to set. A value of "*" means that all request parameters whose names match the
bean. The value attribute tells which value is to be assigned to the given property. If the
parameter's value is null, or the parameter does not exist, then the setProperty action is The
attribute param gives the name of the request parameter whose value the property is to
receive. We can't use both value and param, but it is permissible to use neither.
Types of Expressions:
The 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.
1. Value Expressions:
Value expressions can be further categorized into rvalue and Ivalue expressions. The rvalue
expressions are those that can read data, but cannot write it. Ivalue expressions can both
read and write data.
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 Ivalue expressions. Consider the following two value expressions:
$
[customer.nam
e}
#[customer.na
me]
The first expression accesses the name property, gets its value, adds the value to the
response, and gets rendered on the page. The same can happen with the second expression.
However, the tag handler can defer the evaluation of this expression to a later time in the
page lifecycle, if the technology using this tag allows.
In the case of JavaServer Faces technology (JSF), the latter tag's expression is evaluated
immediately during an initial request for the page. In this case, this expression acts as an
rvalue expression. During a postback request, this expression can be used to set the value of
the name property with user input. In this case, the expression acts as an Ivalue expression.
2. Method Expressions:
A method expression is used to invoke an arbitrary public method of a bean, which can return
a result.
In JavaServer Faces technology, a component tag represents a component on a page. The
component tag uses method expressions to invoke methods that perform some processing for
the component. These methods are necessary for handling events that the components
generate and validating component data, as shown in this example:
<h:form> <h:inputText
id="name"
value="#[customer.name]"
validator="#{customer.validateName]
"/>
<h:commandButton id="submit" action="#[customer.submit]"/>
</h:form>
Method expressions can be used only in tag attributes and only in the follow ways:
With a single expression construct, where bean refers to a JavaBeans compone and
method refers to a method of the JavaBeans component:
<some:tag value="#[bean.method]"/>
The is evaluated to a method expression, which is passed to the handler. The method
represented by the method expression can then be invoked later
1. Restriction Operators:
These are also referred as Filtering operators. These are an operation to restrict the result
set such that it has only selected elements satisfying a particular condition. There are two
operators of this type.
I. Where: Filter values based on a predicate function.
II. OfType: Filter values based on their ability to be as a
specified type. Ex: products.where(p->p.productPrice >=100)
3. Partitioning Operators: These divide an input sequence into two separate sections
without rearranging the elements of the sequence and then returning one of them. There are
four operators of this type.
I. Skip: Skips some specified number of elements within a sequence and returns the
remaining ones.
II. SkipWhile : Same as that of Skip with the only exception that number
of elements to skip are specified by a Boolean condition.
III. Take: Take a specified number of elements from a sequence and skip the
remaining ones.
IV. TakeWhile : Same as that of Take except the fact that number of
elements to take are specified by a Boolean condition.
Ex: products.take(500)
Ex: products.skip(4) Ex: products.takeWhile
(Boolean b) Ex: products.skipWhile(Boolean b)
Q. 11 Explain Conditional or Flow Control Statements in XML Tag Library with examples.
Conditional or Flow Control Statements Flow control XML actions explained below:
1. The <x:if> tag allows us to process the body content of the <x:if> tag if a condition
evaluates to true and consists of two variants, with or without a body.
The following code snippets shows the two variants of the <x:if> tag where the
square brackets indicate optional attributes and the curly bracers indicate a choice of options
within them where the default is underlined.
// Evaluate XPath expression and save test condition result to var
<x:if select="XPathExpression"
var="varName" [scope="[page request |
session | application}"]/>
// Evaluate XPath expression and optionally save test condition result to var.
// Process body content if condition evaluates to true.
<x:if select="XPathExpression"
[var="varName"] [scope="[page request
session application}"]>
body content to process
</x:if>
2. The <x:choose> tag is used in conjunction with the <x:when> and <x:otherwise> tags
and works in a similar way to the switch.. case.. default Java conditional. There are two
variants of the <x:choose> tag as shown in the code snippets below:
//<x:choose> and <x:when>
<x:choose>
<x:when select="XPathExpression"> expression evaluates to true
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT
3
</x:when>
<x:when select="XPathExpression"> expression evaluates to true
</x:when>
</x:choose>
1. JSTL Query Tag <sql:query> provides capability to fetch the data from databased by
executing query directly from JSP and it can be stored in a variable to use later with
the help of scope attribute.
Syntax:
<sql:query var"<string>" scope="<string>" sql="<string>" dataSource="<string>
startRow="<string>" maxRows="<string>"/>
Attributes:
2. The <sql:update> tag executes the provided SQL query through its body or
through its sql attribute. JSTL Update Tag provides capability to write insert,
update or delete statements directly from JSP.
Syntax:
<sql:update var="<string>" scope="<string>" sql="<string>" dataSource="<string>"/>
Example:
<sql:setDataSource
driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/database_n
ame" var="localSource"
user="database_user"
password="database_passwor
d"/>
<sql:update dataSource="${snapshot}" var="count">
INSERT INTO Employees VALUES (333, 27, 'Anamika', 'Rajput');
</sql:update>
<sql:query dataSource="${localSource}"
var="result"> SELECT * from Employees;
</sql:query>
<table border="1" width="100%">
<tr>
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT
3
<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>
</c:forEach>
</table>
Q. 13 What is EL? Explain immediate EL, deferred EL, LValue and RValue in detail.
Expression Language:
JSP Expression Language provides a way to simplify expressions.
It is a simple language used for accessing implicit objects. Java
classes and for manipulating collections in an elegant manner. It
is the newly added feature in JSP technology version 2.0.
The expression language also allows page authors to use
simple expressions to dynamically read data from JavaBean
components. Unified Expression Language allows usage of
simple expressions to perform the following tasks:
ata stored in JavaBeans
components, various data structures and implicit objects.
components.
Can only read data, but cannot write data. Expressions that use
deferred valuation syntax are always rvalue expressions.
C) Iterator Actions:
Iterator Actions simplify iteration through collection of objects.
1. <c:forEach >
The <c:forEach> tag is a commonly used tag because it repeats
the nested body content for fixed number of times or over
collection.
Example
<c:forEach var = "i" begin = "1" end =
"5"> Item <c:out value = "${i}"/><p>
</c:forEach>
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT
3
This will print the values from 1 to 5.
2. <c:forTokens>
The <c:forTokens> tag iterates over tokens which is
separated by the supplied delimeters. It is used for break a
string into tokens and iterate through each of the tokens to
generate output.
This tag has similar attributes as <c:forEach> tag except one
additional attributes delims which is used for specifying the
characters to be used as delimiters.
Example
<c:forTokens items=”Chris-Steve-Liza" delims="-" var="name">
<c:out value="${name}"/><p>
</c:forTokens>
This will print the names as separate tokens.
Objects with page scope are accessible only within the page in
which they're created. The data is valid only during the
processing of the current response; once the response is sent
back to the browser, the data is no longer valid. If the request is
forwarded to another page or the browser makes another request
as a result of a redirect, the data is also lost.
//Example of JSP Page Scope
<jsp:useBean id="employee" class="EmployeeBean" scope="page" />
2. Request Scope:
Objects with request scope are accessible from pages processing the
same request in which they were created. Once the container has
processed the request, the data is released. Even if the request is
forwarded to another
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT
3
page, the data is still available though not if a redirect is required.
//Example of JSP Request Scope
<jsp:useBean id="employee" class="EmployeeBean" scope="request" />
3. Session Scope:
Objects with application scope are accessible from JSP pages that
reside in the same application. This creates a global object that's
available to all pages.
Application scope uses a single namespace, which means all your
pages should be careful not to duplicate the names of application
scope objects or change the values when they're likely to be read
by another page (this is called thread safety). Application scope
variables are typically created and populated when an
application starts and then used as read-only for the rest of the
application.
//Example of JSP Application Scope
<jsp:useBean id="employee" class="EmployeeBean" scope="application" />
Q. 16 Develop a simple JSP application to accept values from html page and display on next page.
(Name-txt, age-txt, hobbies-checkbox, email-txt, gender-radio button).
HTML Form :
<Html>
<form action="Show.jsp" >
<br> Enter Name <input type=text name=txtName >
<br> Enter Age <input type=text name=txtAge >
<br> Select Hobbies <input type=checkbox name=txtHob value=Reading >Reading
<input type=checkbox name=txtHob value=Singing >Singing
<br> Select Gender <input type=radio name=txtGender value=Male >Male
<input type=radio name=txtGender value=Female >Female
<input type=radio name=txtGender value=Other >Other
<input type=submit>
</form>
</HTML>
JSP Code :
Your Name <
%=request.getParameter("txtName") %> Your
Age <%=request.getParameter("txtAge") %>
<%
foreach(i in request.getParameters("txtHob")) out.println("<br>"+i);
%>
Gender Selected <%=request.getParameter("txtGender") %>
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT
3
Q. 17 Explain the <jsp:useBean > tag with its attribute. Support your answer with suitable code
snippet.
In this example, we are simply invoking the method of the Bean class.
For the example of setProperty, getProperty and useBean tags, visit next page.
Calculator.java (a simple Bean class)
1. package com.javatpoint;
2. public class Calculator{
3.
4. public int cube(int n){return n*n*n;}
5.
6. }
index.jsp file
1. <jsp:useBean id="obj" class="com.javatpoint.Calculator"/>
2.
3. <%
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT
3
4. int m=obj.cube(5);
5. out.print("cube of 5 is "+m);
6. %>
Q. 18 What is wrong in using JSP scriptlet tag? How JSTL fixes JSP scriptlet shortcomings?
The scriptlet tags provided by JSP technology should not be used to embed your
business logic and then rendering the view. This is because of the following
disadvantages:
1. No Code Reusability: Using the scriplet tags on JSP reduces the code reusability as if
done so than view will be binded to that scriplet tags.
2. Poor structure of JSP page: Scriptlet tags if used on JSP page for view management
does result in a structure of code that is difficult to understand and interpret.
3. Reduced readability of html code: Understanding the HTML of the final view
4. Increases efforts to understand the JSP: Because view is dependent conditions
defined in the scriplet tags, it do takes time to understand the JSP.
5. Prone to exception and hence no view at all: If any exception occurs on the JSP
because of business logic, there will be no view at all.
How JSTL fixes JSP Scriptlet's shortcomings? (Advantages of JSTL over JSP)
1. Scriptlets (Java codes within JSP) are complex and are extremely hard to be
maintained. Unlike scriptlets, JSTL makes our JSP readable and maintainable.
2. HTML programmer may find it hard to modify the JSP with the scriptlets as he or she
may not have the Java programming knowledge. However, if we are using JSTL to
replace our scriptlets, HTML programmer can easily understand on what's going on in
the JSP as JSTL is in the form of XML tags similar to the normal HTML tags.
3. JSTL requires less code compared to scriptlets.
4. Standard Tag: It provides a rich layer of the portable functionality of JSP pages. It's
easy for a developer to understand the code.
5. The name of each tag in JSTL is self-explanatory and is easy to understand.
6. Automatic Java beans Introspection Support: It has an advantage of JSTL over JSP
scriptlets. JSTL Expression language handles JavaBean code very easily. We don't
need to downcast the objects, which has been retrieved as scoped attributes. Using
JSP scriptlets code will be complicated, and JSTL has simplified that purpose.
7. Easier for humans to read : JSTL is based on XML, which is very similar to
HTML Hence, it is easy for the developers to understand.
8. Easier for computers to understand: Tools such as Dreamweaver and front page are
generating more and more HTML code. HTML tools do a great job of formatting HTML
code. The HTML code is mixed with the scriplet code. As JSTL is expressed as XML
compliant tags, it is easy for HTML generation to parse the JSTL code within the
document.
9. Fast Development JSTL provides many tags that simplifies the JSP.