0% found this document useful (0 votes)
29 views

Enterprise Java Unit 3

Java ek or

Uploaded by

nexo8356
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Enterprise Java Unit 3

Java ek or

Uploaded by

nexo8356
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT

3
Q.1 What are the benefits of using JSP?/ Explain the reason why use JSP?

JSP has the following benefits:


1. Nobody can borrow the code: Since JSP page are written, runs and remains on the
server, nobody can copy the logic written in a jsp page even if they wanted to. Thus,
security of the code is maintained.
2. Faster loading of pages: Response page customization as requested by the user is
done at the server side itself thus no extra code or content is sent to the client side
resulting in faster loading of pages.
3. No Browser compatibility issues: Since JSP runs on the server side, the developer ends
up sending standard HTML to the user browser. This largely eliminates cross browser
compatibility issues.
4. JSP Support: JSP is supported by a number of Web Servers. Built-in Support for JSP is
available in Java Web Server from Oracle.
5. Compilation: In JSP technology, each JSP page is compiled into executable code the
first time it is requested and invokes the resulting code directly on all subsequent
requests. When coupled with a persistent JVM, this allows the server to process request
to JSP pages much faster.
6. Similarity to HTML: A JSP page looks a lot like a HTML or XML page except for the
business logic written either in scripting elements or JSP tags or both. Writing the
business logic in JSP tags brings consistency to the coding style used on the entire JSP
page.
7. Separation of logic from view It enables to separate presentation layer with the
business logic layer in the web application.

Q. 2 Explain disadvantages of JSP.

The disadvantages of JSP are:


1. Attractive Java code: Putting Java code within a webpage is really bad design, but
JSP makes it tempting to do just that. Avoid this as far as possible.
2. Java Code Required: To do relatively simple things in JSP can actually demand putting
Java code in a page. A page needs to determine the context root of the current web
application, perhaps to create a link to the web applications,home page. This is done
using Java code in JSP.
<a href=’<%=request.getContextPath%>/index.html’>Home Page Java code can be
avoided by using
<jsp:getProperty> but that makes the code spec even more complex.
<a href=’ <jsp:getProperty name=”request”
property=”contextPath”/>/index.html’>Home Page</a>
3. Simple Tasks are Hard to Code: Even including page headers and footers is a bit
difficult with JSP. In JSP the best way to do this is as follows:
<jsp:getProperty name=”request” property=”contextPath”/>
/*Some content here*/
<% @include file=”/footer.jsp”;%>
4. Occupies a lot of space: JSP pages require about double the disk space to hold the
page. Because JSP pages are translated into class files, the server has to store the
resultant class files with the JSP pages.
5. Debugging not easy: It is hard to trace JSP pages error because JSP pages are
translated to servlet before the compilation process.
6. Difficult Looping in JSP: Looping in JSP is a bit complicated.
7. Database Connection not easy: Database connectivity is not as easy as it should be.
Most of the servlet engine vendors do not support connection pooling natively, as of
this day. Consequently, one has to write a lot of custom code to do the job.
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT
3
Q. 3 Write a short note on life cycle of 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.

Q. 4 Explain types of directives in JSP.

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

1. Jsp Page Directive:


 The page directive is used to provide instructions to the container.
 These instructions pertain to the current JSP page.
 By convention, page directives are coded at the top of the JSP page.
 Following is the basic syntax of the page directive:
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT
3
<%@ page attribute = "value" %>
 The following are the most common attributes associated with the page directive:

Sr.No Attribute and


. Example
1. language
Defines the programming language used in the JSP
page. Eg:< %@ page language="java"%>
2. import
Specifies a list of packages or classes for use in the JSP as the
Java import statement does for Java classes.
Eg:< %@ page import="java.util.Date" %>
3. contentType
Defines the character encoding scheme.
Eg:< %@ page contentType=application/msword %>
4. extends
Specifies a superclass that the generated servlet must
extend. Eg:< %@ page extends =
"somePackage.SomeClass" %>
5. isErrorPage
Indicates if this JSP page is a URL specified by another JSP
page's errorPage attribute.
Eg:< %@ page isErrorPage="true" %>
6. session
Specifies whether or not the JSP page participates in HTTP
sessions. Eg:< %@ page session = "true" %>
7. info
The info attribute lets you provide a description of
the JSP. Eg:< %@ page info = "This is a JSP Page"
%>

2. JSP 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.
 Following is the basic syntax of the page include:
<%@ include file = "relative url">
 The file attribute:
A page-relative or context-relative URI path to the file that will be included at the
current position in the file.
 This attribute includes a static file ,merging its content with the including
page before the combined result is converted to a JSP page implementation
class.
 A page can contain multiple include directives.
3. JSP Taglib Directive:
 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.
 Custom Tags allow developers to hide complex server side code spec from web
designers.
 A taglib directive in a JSP is a link to an XML document that describes a set of
custom tag.
 This XML document also determine which Tag Handler class implements the
action of each tag. The XML document names the tag library which holds the
custom tags.
 The JSP engine uses this tag library to determine what to do when it comes
across custom tags.
 The taglib directive follows the syntax given below:
<%@ taglib uri = "uri" prefix = "prefixOfTag" >
 The uri attribute:
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT
3
A Uniform Resource Identifier (URI) that identifies the Tag Library
Descriptor ,which is used to uniquely name the set of custom tags and inform
the server what to do with the specified tags.
 The prefix attribute:
It defines the prefix string in : pair and informs the JSP container which bits of
markup are custom tags.

Q. 5 What are the implicit objects in JSP?


 The JSP engine produces these objects during the translation phase (i.e., at the time
of translation from JSP to Servlet).
 They are being formed within the service method so that JSP developers can use
them directly in Scriptlet without declaration and initialization.
 There are 9 implicit objects in JSP as follows:

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 %>

Q. 6 Explain disadvantages of JSTL.

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.

Q. 8 How to set and access the properties of java bean in JSP?

Setting the Properties of the Bean:


The JSP 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:
 We can use JSP:setProperty after, but outside of, a JSP:useBean element, as follows:
<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 way in which JSP:setProperty can appear is inside the body of a JSP:useBean
element, as follows: <JSP:use Bean id="myName"...>
<JSP:setProperty name="myName" property="someProperty" .../>
</JSP:useBean>
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT
3
In this case the JSP:setProperty is executed only if a new object was instantiated, not if an
existing one was found. Property names will be passed to the appropriate setter methods.

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.

Accessing the Properties of the Bean:


The getProperty action is used to regain the value of a given property and converts to a string,
and finally inserts it into the output. The getProperty action has only two attributes, both of
which are required.
Syntax: <JSP:use Bean id="myName" .../>
….
<JSP:getProperty name="myName" property="someProperty" .../>
In <ISP:getProperty> Action the name attribute gives the name of Bean that has a property
to be retrieved. In this case the Bean must have been previously defined. The property
attribute states the name of the Bean property to be retrieved.
Example: We have to define a TestClass bean which we will use in our example
// TestClass.java
package testAction;
public class TestClass
{
private String msg = "Hello
JSP..."; public String getMsg()
{ return(msg);
}
public void setMsg(String
msg) { this.msg = msg;
}
}
We have to compile above code to generated TestClass.class file and make sure
that copied TestClass.class file in C:\apache-tomcat-7.0.2\ webapps\WEB-INF\
classes\testAction folder and CLASSPATH variable should also be set to this folder.
Now use the following code in home.JSP file which loads the bean and sets/gets a simple
String parameter:
<html> <head> <title>Using JavaBeans in JSP</title> </head>
<body> <center> <h2>Using JavaBeans in JSP</h2> <JSP:useBean id="test" class="test
Action.TestClass" />
<JSP:setProperty name="test" property="msg" />
<p>Here we got the message</p>
<JSP:getProperty name="test" property="msg" />
</center> </body> </html>

Now we have to load home.JSP, it would display following


result: Using JavaBeans in JSP
Here we got the
message Hello JSP...
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT
3

Q. 9 What are the types of Expression available in EL?

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

 With text only.


<some tag value="sometext"/>
Method expressions support literals primarily to support action attribu JavaServer Faces
technology.
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT
3
Q. 10 Write short note on Restriction, Projection and Partitioning Operators in EL.

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)

2. Projection Operators: Projection is an operation in which an object is transformed into an


altogether new form with only specific properties. There are two operators of this type.
I. Select: The operator projects values on basis of a transform function.
II. SelectMany: The operator project the sequences of values which are
based on a transform function as well as flattens them into a single
sequence.
Ex: products.select(p->p.productName) Ex: products.selectMany(p->p.productType)

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>

// <x:choose> <x:when> and <x:otherwise>


<x:choose>
<x:when
select="XPathExpression">
expression evaluates to true
</x:when>
<x:when
select="XPathExpression">
expression evaluates to true
</x:when> <x:otherwise>
no expressions have evaluated to true
</x:otherwise>
</x:choose>
3. The <x:forEach> tag evaluates the given XPath expression and repeats
its nested body content over the result, setting the context node to each
element in the iteration.
The following code snippet shows the syntax of the <x:forEach> tag where the square
brackets indicate optional attributes.
// Evaluates given XPath expression and iterate over body content
<x:forEach ["var="varName"] select="XPathExpression"
["varStatus="varStatusName"]["begin="begin"]["end="end"]
["step="step"]> body content
</x:forEach>

Q. 12 How to query and update data in JSTL?

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:

Name Required Typ Description


e
var True java.lang.String Name of the variable to
store the query result.
This variable is of
javax.servlet.jsp.jstl.sql.Res
ult.
scope False java.lang.String Scope of the var to be
placed in.
sql False java.lang.String SQL query to execute.
dataSource False java.lang.String Datasource relative path
in the JNDI tree.
startRow False java.lang.String Starting index to show the
results. If specified, the
results from the index
specified here
will be displayed.
maxRows False java.lang.String The maximum number of
rows to be fetched from
the query.
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT
3
Example:
<sql:setDataSource var="myDS" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test" user="root" password=""/>
<sql:query dataSource="${myDS]"
var="citizens"> SELECT * from citizens;
</sql:query>
<table border="1">
<c:forEach var="row" items="${citizens.rows}">
<tr>
<td><c:out value="${row.ssn}"/></td>
<td><c:out value="${row.first_name}"/></td>
<td><c:out value="${row.last_name}"/></td>
<td><c:out value="${row.address}"/></td>
<td><c:out value="${row.telephone}"/></td>
</tr>
</c:forEach>
</table>

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

Nam Required Type Description


e
var False java.lang.String Name of the
variable which
stores the count
of the rows
affected after
the query
execution.
scope False java.lang.String Scope for var
to store.
sql False java.lang.String SQL query to
execute
dataSource False java.lang.String Associated data
source of
the
database

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.

Types of Evaluation Expressions:


Unified EL supports two types of evaluation expressions:
Immediate and Deferred evaluation
1. Immediate Evaluation:
Immediate evaluation means that the expression is evaluated and the
result returned as soon as the page is first rendered.
Syntax:
${<Expression>}
Here, Expression stands for valid expression.
The following example shows a tag whose value attribute
references an immediate evaluation expression that updates the
quantity of books retrieved from the backing bean named
catalog:
<h:outputText value="${catalog.bookQuantity}" />
2. Deferred Evaluation:

Deferred evaluation means that the technology using the


expression language can use its own machinery to evaluate the
expression sometime later during the page’s lifecycle, whenever
it is appropriate to do so.
Syntax:
#{<Expression>}
Here, Expression stands for valid expression.
Because of its multiphase lifecycle, JavaServer Faces technology
uses mostly deferred evaluation expressions. During the lifecycle,
component
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT
3
events are handled, data is validated, and other tasks are
performed in a particular order. Therefore, a JavaServer Faces
implementation must defer evaluation of expressions until the
appropriate point in the lifecycle.
Other technologies using the EL might have different reasons for
using deferred expressions.
The following example shows a JavaServer Faces h:inputText tag,
which represents a field component into which a user enters a
value. The h:inputText tag’s value attribute references a
deferred evaluation expression that points to the name property
of the customer bean:
<h:inputText id="name" value="#{customer.name}" />
Value Expressions:
The unified EL provides two types of value expressions:

Can only read data, but cannot write data. Expressions that use
deferred valuation syntax are always rvalue expressions.

Can read and write data. Expressions that uses deferred


evaluation syntax can act as both Rvalue and Lvalue
expressions.

Q. 14 Explain JSTL core Tag Library.

JSTL core Tag Library:


The Core Tag Library contains tags that are essential to nearly any Web application.
Examples of core tag libraries are looping, evaluation of expression and basic input and
output.
The URI of the Core Tag Library is “http://java.sun.com/jsp/jstl/core” and
prefix is c. The syntax used for including JSTL Core tags library in your JSP
is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c" %> The Core Tag Library consists of four
distinct functional sections:
A) General - Purpose Actions: These actions allow adding and removing
variables ,displaying variable values and enclosing a group of tags within a try-
catch block.
1. <c:out>
The < c:out> tag displays the result of an expression. This is almost similar to the way
<%= %> works.
Example:
<c:out value = "${'Hello World‟}"/>
This will print Hello World as a response.
2. <c:set>
The <c:set> tag sets the result of an expression evaluation in a
'scope'. Example:
<c:set var = "salary" scope = "session" value =
"${2000}"/> This will set a variable names session
with the value 2000. 3.<c:remove >
The <c:remove > tag removes a scoped variable (from a particular scope, if
specified). Example:
<c:remove var = "salary"/>
This will remove the variable named salary.
4. <c:catch>
The <c:catch> tag catches any Throwable that occurs in its body and optionally
exposes it. Example:
<c:catch var ="catchException">
<% int x = 5/0;%>
</c:catch>
This code block will catch ArithmeticException.
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT
3
B) Conditional Actions Or Flow Control Statements : Conditional Actions are used for
conditional processing within a JSP page.
1. <c:if>
The <c:if> tag evaluates an expression and displays its body content only if the
expression evaluates to true.
Example:
<c:if test = "${salary > 20000}">
<p>My salary is: <c:out value = "${salary}"/><p>
</c:if>
This will print the statement within <c:if > tag if the condition mentioned in test
evaluates to true.
2. <c:choose>,<c:when>,<c:otherwise>:
The <c:choose> works like a Java switch statement in that it lets you choose between
a number of alternatives. Where the switch statement has case statements, the tag
<c:choose> has <c:when> tags. Just as a switch statement has the default clause to
specify a default action, <c:choose> has
<c:otherwise> as the default
clause. Example:
<c:set var="number1" value="${222}"/>
<c:set var="number2" value="${12}"/>
<c:set var="number3" value="${10}"/>
<c:choose>
<c:when test="${number1 < number2}">
${"number1 is less than number2"}
</c:when>
<c:when test="${number1 <= number3}">
${"number1 is less than equal to number2"}
</c:when>
<c:otherwise>
<c:out value=" ${'number1 is largest number!'}"/>
</c:otherwise>
</c:choose>Example
<c:set var="number1" value="${222}"/>
<c:set var="number2" value="${12}"/>
<c:set var="number3" value="${10}"/>
<c:choose>
<c:when test="${number1 < number2}">
${"number1 is less than number2"}
</c:when>
<c:when test="${number1 <= number3}">
${"number1 is less than equal to number2"}
</c:when>
<c:otherwise>
<c:out value=" ${'number1 is largest number!'}"/>
</c:otherwise>
</c:choose>

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.

D) Url Related Actions:


These actions are used to import resources, redirect HTTP responses ,create URLs or
encode a request of parameters.
1. <c:redirect>
The < c:redirect > tag redirects the browser to a new
URL. Example:
<c:redirect
url="http://abc.com"/> This
will redirect to abc.com
2. <c:url>
The < c:url > tag creates a URL with optional query parameter.
It is used for url encoding or url formatting. This tag
automatically performs the URL rewriting operation.
Example:
<c:url value="/Register.jsp"/>
3. <c:param>
The < c:param > tag add the parameter in a containing 'import'
tag's URL. Example:
<c:url value="/index.jsp" var="completeURL"/>
<c:param name="user" value="Ann"/>

Q. 15 Explain the various scope of JSP application.

SCOPE OF JSP OBJECTS:


The availability of a JSP object for use from a particular place of
the application is defined as the scope of that JSP object. Every
object created in a JSP page will have a scope. Object scope in JSP
is segregated into four parts and they are page, request, session
and application.
1. Page Scope:

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 session scope are accessible from pages processing


requests that are in the same session as the one in which they
were created. A
session is the time users spend using the application, which ends when they close
their browser, when they go to another Web site, or when the
application designer wants (after a logout, for instance). So, for
example, when users log in, their username could be stored in
the session and displayed on every page they access. This data
lasts until they leave the Web site or log out.
//Example of JSP Session Scope
<jsp:useBean id="employee" class="EmployeeBean" scope="session" />
4. Application 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.

<jsp:useBean > tag:


The jsp:useBean action tag is used to locate or instantiate a bean class. If bean object of the
Bean class is already created, it doesn't create the bean depending on the scope. But if object
of bean is not created, it instantiates the bean.
Syntax of jsp:useBean action tag:
<jsp:useBean id= "instanceName" scope= "page | request | session |
application" class= "packageName.className" type=
"packageName.className" beanName="packageName.className | <%=
expression >" >
</jsp:useBean>
Attributes and Usage of jsp:useBean action tag
1. id: is used to identify the bean in the specified scope.
2. scope: represents the scope of the bean. It may be page, request, session or
application. The default scope is page.
o page: specifies that you can use this bean within the JSP page. The default scope
is page.
o request: specifies that you can use this bean from any JSP page that processes
the same request. It has wider scope than page.
o session: specifies that you can use this bean from any JSP page in the same
session whether processes the same request or not. It has wider scope than
request.
o application: specifies that you can use this bean from any JSP page in the same
application. It has wider scope than session.
3. class: instantiates the specified bean class (i.e. creates an object of the bean class) but
it must have no-arg or no constructor and must not be abstract.
4. type: provides the bean a data type if the bean already exists in the scope. It is
mainly used with class or beanName attribute. If you use it without class or beanName,
no bean is instantiated.
5. beanName: instantiates the bean using the java.beans.Beans.instantiate() method.

Simple example of jsp:useBean action tag

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.

You might also like