Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Why we use JSP?

Ans: JSP is used to create dynamic web content. In this JSP tags are used to insert JAVA code into
HTML pages. It is an advanced version of Servlet Technology. It is a Web based technology helps
us to create dynamic and platform independent web pages.

2.Describe JSP architecture.


Architecture of JSP
JSP architecture is a three-tier architecture consisting of a web server, client, and database.

Web Server: It uses a JSP engine like a container that processes JSP. E.g., Apache
Tomcat. This engine intercepts the request for JSP and provides a runtime environment for
the understanding and processing of JSP files. It reads, parses, builds Java Servlet,
Compiles, Executes Java code, and returns the HTML page to the client.

Client: It is the web browser/application on the user’s side.

Database: It is used to store the user’s data. The webserver has access to the database.

JSP Architecture Flow


1. When a user navigates to a page ending with a .jsp extension in their web browser, the
web browser sends an HTTP request to the webserver.

2. The webserver checks if a compiled version of the JSP page already exists.

3. If the JSP page's compiled version does not exist, the file is sent to the JSP Servlet engine,
it converts it into servlet content (with .java extension). This process is known as translation.
4. Then after translated .java file of the servlet is compiled into the Java servlet .class file.
This process is known as compilation.
5. In the last step, the compiled .class file of the servlet is executed, and the result (HTML) is
sent back to the client machine as an HTTP response.

3. Life Cycle of JSP. Which JSP lifecycle methods can be overridden?

Ans:
*Lifecycle of JSP
A JSP lifecycle can be defined as the process that starts with its creation which is further
translated into a servlet, and then the servlet life cycle comes into play.
Following steps are involved in a JSP lifecycle:
• Translation
• Compilation
• ClassLoading
• Instantiation
• Initialization
• Request Processing
• Destroy
• Translation - This phase deals with the syntactic correctness of the page. JSP code is checked by
the JSP container and is parsed by it to generate the servlet source code. The web container
automatically translates the index.jsp file into index.java.

• Compilation - Here, the JSP container compiles the JSP class source code. It converts the
index.java file into an index.class file. The translation of the java source to its implementation
class can occur at any given time between the deployment of the JSP page into the container
and processing of the JSP page.

• ClassLoading - In this phase, the servlet class loaded from the JSP source is loaded into the
container.

• Instantiation - In this phase, an instance of the class is generated. The container manages one or
more instances by responding to the requests.

• Initialization - In this phase, the container invokes the init method of the JSP class. After that,
servlet configuration with the init parameter is configured. Now, JSP can handle the client
requests. Most often, the translation and initialization in JSP happen as soon as the first request
for a JSP comes.

• Request Processing - This is the most time-consuming phase of the JSP. Here, the JSP page
processes the requests from a client. The request processing phase is multi-threaded. A new
thread is used for every request, and a servlet request and response object are created. After
this, the _jspService() method is called. This method cannot be overridden.

• Destroy - The last phase of the JSP lifecycle is destroyed. The JSP class is unloaded or removed
from the container in this phase. It is done when the application is undeployed or when the
server is down. This is done using the jspDestroy() method and can be overridden.

Let’s try to understand the JSP lifecycle methods in a more elaborative way:
jspInit(): This is declared on the JSP page. This method is called only once in the complete lifecycle of
JSP. This is used to initialize configuration params in a deployment descriptor. This method can be
overridden using a JSP declaration scripting element.

_jspService(): It is invoked by the JSP container for each client request. This method passes request and
response objects. It cannot be overridden, and hence, it starts with an underscore. It is defined and
declared in the HttpJspPage interface.

jspDestroy(): This is used for shutting down application/container. This method is called only once in the
complete JSP lifecycle when JSP is unloaded from the memory. This method should be overridden only
to release resources created in the JSP init method.

*MENTION JSP lifecycle methods that can be overridden.

Ans: jspInit() and jspDestroy() methods can be overridden in JSP lifecycle using JSP declaration scripting
element.

The jspInit() method is overridden to create common resources that can be used in the JSP service
method, and the jspDestroy() method is overridden to release the common resources which were
created using jspInit().

4. What is the function of scriplet tag?


Ans: Scriptlet Tag allows you to write java code inside JSP page. Scriptlet tag implements
the _jspService method functionality by writing script/java code. Syntax of Scriptlet Tag is as follows :

<% JAVA CODE %>

5. How we declare a variable in JSP?


This declares one or more variables or methods for use later in the JSP source file. It must contain at
least one complete statement. You can declare any number of variables or methods within one
declaration tag, but you have to separate them by semicolons. The declaration must be valid in the
scripting language used in the JSP file.You can add method to the declaration part.

6.How we use expression in JSP?


The expression tag is used to evaluate Java's expression within the JSP, which then converts the result
into a string and forwards the result back to the client browser via the response object. Essentially, it is
implemented for printing the result to the client (browser). An expression tag can hold any java
language expression that can be employed as an argument to the out.print() method.

The syntax of the expression tag in JSP looks something like:

Syntax:

<%= expression %>


7. List predefined actions in JSP
JSP Action Tags

JSP Action Tags

There are many JSP action tags or elements. Each JSP action tag is used to perform some specific tasks.

The action tags are used to control the flow between pages and to use Java Bean. The Jsp action tags are
given below.

JSP Action Tags Description

jsp:forward forwards the request and response to another resource.

jsp:include includes another resource.

jsp:useBean creates or locates bean object.

jsp:setProperty sets the value of property in bean object.

jsp:getProperty prints the value of property of the bean.

jsp:plugin embeds another components such as applet.

jsp:param sets the parameter value. It is used in forward and include mostly.

jsp:fallback can be used to print the message if plugin is working. It is used in jsp:plugin.

8. List the JSP implicit objects


JSP Implicit Objects

There are 9 jsp implicit objects. These objects are created by the web container that are available to all
the jsp pages.

The available implicit objects are out, request, config, session, application etc.

A list of the 9 implicit objects is given below:


Object Type Description

out JspWriter This is the PrintWriter object used to send output to the client

request HttpServletRequest The is the HttpServletRequest object associated with the request.

response HttpServletResponse This is the HttpServletResponse object associated with the


response to the client.

config ServletConfig This is the ServletConfig object associated with the page.

application ServletContext This is the ServletContext object associated with application


context.

session HttpSession This is the HttpSession object associated with the request.

pageContext PageContext The encapsulates use of server-specific features like higher


performance JspWriters.

page Object This is simply a synonym for this, and is used to call the methods
defined by the translated servlet class.

exception Throwable The Exception object allows the exception data to be accessed by
designated JSP.

11. How many kinds of directives in JSP?


Directives supply directions and messages to a JSP container. The directives provide global information
drawabout the entire page of JSP. Hence, they are an essential part of the JSP code. These special
instructions are used for translating JSP to servlet code.

There are 3 types of directives:

1.Page directive

2.Include directive

3.Taglib directive
Let us now discuss each of them in detail.

Page Directive: The page directive is used for defining attributes that can be applied to a complete JSP
page. You may place your code for Page Directives anywhere within your JSP page. However, in general,
page directives are implied at the top of your JSP page.
The basic syntax of the page directive is: <%@ page attribute = "attribute_value" %>

Include Directive:

The JSP "include directive" is used to include one file in another JSP file. This includes HTML, JSP, text,
and other files. This directive is also used to create templates according to the developer's requirement
and breaks the pages in the header, footer, and sidebar.

To use this Include Directive, you have to write it like:

<%@ include file = "relative url" >

Taglib Directive:

The JSP taglib directive is implemented to define a tag library with "taglib" as its prefix. Custom tag
sections of JSP use taglib. JSP's taglibdirective is used as standard tag libraries.

To implement taglib, you have to write it like this:

<%@ taglib uri="uri" prefix="value"%>

12. Give few names of mouse events in HTML


The MouseEvent Object

Events that occur when the mouse interacts with the HTML document belongs to the MouseEvent
Object.

MouseEvent Properties and Methods

Property/Method Description

altKey Returns whether the "ALT" key was pressed when the mouse
event was triggered

button Returns which mouse button was pressed when the mouse event
was triggered
buttons Returns which mouse buttons were pressed when the mouse
event was triggered

clientX Returns the horizontal coordinate of the mouse pointer, relative


to the current window, when the mouse event was triggered

clientY Returns the vertical coordinate of the mouse pointer, relative to


the current window, when the mouse event was triggered

ctrlKey Returns whether the "CTRL" key was pressed when the mouse
event was triggered

getModifierState() Returns true if the specified key is activated

metaKey Returns whether the "META" key was pressed when an event
was triggered

movementX Returns the horizontal coordinate of the mouse pointer relative


to the position of the last mousemove event

movementY Returns the vertical coordinate of the mouse pointer relative to


the position of the last mousemove event

offsetX Returns the horizontal coordinate of the mouse pointer relative


to the position of the edge of the target element

offsetY Returns the vertical coordinate of the mouse pointer relative to


the position of the edge of the target element
pageX Returns the horizontal coordinate of the mouse pointer, relative
to the document, when the mouse event was triggered

pageY Returns the vertical coordinate of the mouse pointer, relative to


the document, when the mouse event was triggered

region

relatedTarget Returns the element related to the element that triggered the
mouse event

screenX Returns the horizontal coordinate of the mouse pointer, relative


to the screen, when an event was triggered

screenY Returns the vertical coordinate of the mouse pointer, relative to


the screen, when an event was triggered

shiftKey Returns whether the "SHIFT" key was pressed when an event was
triggered

which Returns which mouse button was pressed when the mouse event
was triggered

13. Give few names of Key events in HTML

https://www.geeksforgeeks.org/html-event-attributes-complete-reference/
14. Which methods pass information from browser to server?
Ans: Web browsers communicate with web servers using the HyperText Transfer Protocol (HTTP). When
you click a link on a web page, submit a form, or run a search, the browser sends an HTTP Request to the
server.

15.Differences between GET & POST methods in JSP

Ans: here are many differences between the Get and Post request. Let's see these differences:

GET POST

1) In case of Get request, only limited amount of In case of post request, large amount of
data can be sent because data is sent in header. data can be sent because data is sent in body.

2) Get request is not secured because data is exposed in Post request is secured because data is not
URL bar. exposed in URL bar.

3) Get request can be bookmarked. Post request cannot be bookmarked.

4) Get request is idempotent . It means second request Post request is non-idempotent.


will be ignored until response of first request is delivered

5) Get request is more efficient and used more than Post. Post request is less efficient and used less than
get.

16.Why we use filters in JSP?


Ans: The filters can be used in plenty of ways in a web page definition and backend management as all
the data sent over by a user can be successfully translated and encrypted by the Logging
filters and Encryption filters and the data can be transacted or retrieved employing the Tokenizing
filters. Similarly, the user data coming in can be compressed accordingly using the Data Compression
filters.
17.How many kinds of filters in JSP?
Logging Filters: We can use logging filters to log any information in the backend or, over a
server.

Data Compression Filters: As the name suggests, You can use data compression filters to
compress the data to a certain extent.

Tokenizing Filters: We can store and retrieve all the user data using tokenizing filters.

Encryption Filters: Sometimes, we want to encrypt and save user data that is flowing through
the filters. So, encryption filters come into existence and do the job.

Authentication Filters: The authentication filters are employed to accomplish authentication


only based on the preset criteria.

18.What are the major attributes of Page Directives ?

Attribute Name Description

buffer It indicates buffering model for output stream

autoFlush Servlet output buffer behavior is controlled with this attribute

contentType Character encoding scheme related attribute

errorPage Uniform Resource Locator for another JSP that reports Java unchecked runtime
exceptions.

isErrorPage Indicates URL specified by JSP page’s errorPage attribute defined above.

extends Superclass generated Servlet must extend is specified with this attribute

import Similar to Java classes, import attribute is used to list packages or classes for
use in JSP page.
Attribute Name Description

info This attribute is defined as a string accessed by Servlet’s getServletInfo()


method,

isThreadSafe This attribute defines threading model for Servlet

language Declares programming language used in JSP pages.

session Declares JSP page participation in HTTP sessions.

isELIgnored Attribute decides whether to EL expression within JSP will be ignored or not.

isScriptingEnabled Whether scripting elements are allowed for use or not can be decided by this
attribute.

19. What are the functions of Cookies in JSP?

• Cookies are the text files which are stored on the client machine.
• They are used to track the information for various purposes.
• It supports HTTP cookies using servlet technology
• The cookies are set in the HTTP Header.
• If the browser is configured to store cookies, it will keep information until
expiry date.

20. How we create Cookie?


Creating a cookie object

You can make a cookie by calling the cookie constructor with the cookie value and name, both of which
are strings.

Cookie cookie = new Cookie(“Key”,” Value”);

Neither the value nor the name contains the white spaces or the following characters.

[]()=,:@?;
21. How we establish a Data Base connection in JSP?
Java Database Connectivity is a standard API or we can say an application interface present between the
Java programming language and the various databases like Oracle, SQL, PostgreSQL, MongoDB, etc. It
basically connects the front end(for interacting with the users) with the backend for storing data
entered by the users in the table details. JDBC or Java Database Connection creates a database by
following the following steps:

1. Import the database


2. Load and register drivers
3. Create a connection
4. Create a statement
5. Execute the query
6. Process the results
7. Close the connection

22.What is ResultSet?

A ResultSet is a Java object that contains the results of executing an SQL query. In
other words, it contains the rows that satisfy the conditions of the query. The data
stored in a ResultSet object is retrieved through a set of get methods that allows
access to the various columns of the current row. The ResultSet.next method is used
to move to the next row of the ResultSet, making it the current row.

The general form of a result set is a table with column headings and the corresponding
values returned by a query. For example, if your query is SELECT a, b, c FROM
Table1, your result set will have the following form:

a b c
---------- ------------ -----------
12345 Cupertino 2459723.495
83472 Redmond 1.0
83492 Boston 35069473.4

23. Explain how we retrieve data from ResultSet

1. Invoke the Connection. createStatement method to create a Statement object.


2. Invoke the Statement. ...
3. In a loop, position the cursor using the next method, and retrieve data from each column
of the current row of the ResultSet object using getXXX methods. ...
4. Invoke the ResultSet. ...
5. Invoke the Statement.

24.Mention the different kinds of Database Drivers available in JSP. Which type you like best
& why?

JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as
written in Java language.
Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.

25.What are the functions of Metadata?


Metadata has various purposes. It can help users find relevant information and discover resources. It
can also help organize electronic resources, provide digital identification, and archive and preserve
resources.

26.What are the functions of ResultSetMetadata ?


ResultSetMetaData is an interface in java.sql package of JDBC API which is used to get the metadata
about a ResultSet object. Whenever you query the database using SELECT statement, the result will be
stored in a ResultSet object. Every ResultSet object is associated with one ResultSetMetaData object.
This object will have all the meta data about a ResultSet object like schema name, table name, number
of columns, column name, datatype of a column etc. You can get this ResultSetMetaData object
using getMetaData() method of ResultSet.
27. How we execute a group of SQL Statements using executeBatch() method?

28. Difference between Statement and PreparedStatement :

Statement PreparedStatement
It is used when SQL query is to be It is used when SQL query is to be
executed only once. executed multiple times.
You can not pass parameters at You can pass parameters at
runtime. runtime.
Used for CREATE, ALTER, DROP Used for the queries which are to
statements. be executed multiple times.
Performance is better than
Performance is very low. Statement.
It is base interface. It extends statement interface.
Used to execute dynamic SQL
Used to execute normal SQL queries. queries.
We can not use statement for reading We can use Preparedstatement for
binary data. reading binary data.
It is used for DDL statements. It is used for any SQL Query.
We can not use statement for writing We can use Preparedstatement for
binary data. writing binary data.
No binary protocol is used for Binary protocol is used for
communication. communication.

29. When we use CallableStatement?

A CallableStatement can return one ResultSet object or multiple ResultSet objects. Multiple ResultSet
objects are handled using operations inherited from Statement . For maximum portability, a call's
ResultSet objects and update counts should be processed prior to getting the values of output
parameters.
30. Diff. between ResultSet & RowSet
Following are the differences between RowSet and ResultSet:

ResultSet RowSet

A ResultSet always maintains A RowSet can be connected, disconnected from the


connection with the database. database.

It cannot be serialized. A RowSet object can be serialized.

ResultSet object cannot be passed You can pass a RowSet object over the network.
other over network.

ResultSet object is not a JavaBean ResultSet Object is a JavaBean object.You can get a
objectYou can create/get a result RowSet using
set using the RowSetProvider.newFactory().createJdb
the executeQuery() method. cRowSet() method.

By default, ResultSet object is not By default, RowSet object is scrollable and


scrollable or, updatable. updatable.

32. What is JavaBeen?


A JavaBean is a specially constructed Java class written in the Java and coded according
to the JavaBeans API specifications.
Following are the unique characteristics that distinguish a JavaBean from other Java
classes −
• It provides a default, no-argument constructor.
• It should be serializable and that which can implement
the Serializable interface.
• It may have a number of properties which can be read or written.
• It may have a number of "getter" and "setter" methods for the properties.
33. How can we avoid direct access of JSP pages from client browser?

We know that anything inside WEB-INF directory can’t be accessed directly in web application, so we
can place our JSP pages in WEB-INF directory to avoid direct access to JSP page from client browser. But
in this case, we will have to configure it in deployment descriptor just like Servlets. Sample configuration
is given below code snippet of web.xml file.
<servlet>
<servlet-name>Test</servlet-name>
<jsp-file>/WEB-INF/test.jsp</jsp-file>
<init-param>
<param-name>test</param-name>
<param-value>Test Value</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/Test.do</url-pattern>
</servlet-mapping>

34. What are different types of comments in JSP?


Comments tags are used to insert comments in the source code. These comment tags are used to place
some notification or remainders in the source code. Comments are not displayed on the browser, they
only help in document your source code.

Comments are also helpful in debugging the code, because we can comment out the lines of code to
search for errors.

There are three types of comments in JSP :

1) HTML comments :

Html comment syntax are also used in XML and JSP. We can use HTML comments in the JSP page by
using the following syntax:

<!-- This is a comment -->

One thing notice that there is an exclamation (!) point in opening tag,but not in closing tag.
2) JSP Comments :

Jsp Comments are also known as Hidden Comments, because these comments are invisible when jsp
page is translated into servlet internally. Syntax of using JSP comments are :

<%--This is a comment %>

3) Java Comments :

Java Comments are of two types i.e. first is single line comment and other is multiline comment. Java
comments are only allowed in JSP scriptlet tag because java code can only insert into scriptlet tags.

Syntax of using single line comment :

// Single line comment

Syntax of using multiline line comment :

/*

Multiline comment

*/

35. Which implicit object is not available in normal JSP pages?


exception implicit object is not available in normal JSP pages and it's used in JSP error pages only to
catch the exception thrown by the JSP pages and provide useful message to the client.

36. What are the benefits of PageContext implicit object?


PageContext extends JspContext to contribute helpful context details while JSP technology is applied in
a Servlet environment. A PageContext is an instance that gives access to all the namespaces related to a
JSP page, gives access to some page attributes and a layer over the application details. Implicit objects
are connected to the pageContext consequently.
The PageContext class is an abstract class that is formed to be extended to give application-dependent
applications whereof by compatible JSP engine runtime environments. In JSP, pageContext is an instance
of javax.servlet.jsp.PageContext.

The entire JSP page is represented by the PageContext object. This object is considered as a method to
obtain detail about the page while keeping away from most of the execution information.

For each request, the credentials to the response and request objects are saved by this pageContext
object. By accessing attributes of the pageContext object, the out, session, config, and application
objects are obtained.

This pageContext object further holds information regarding the directives provided to the JSP page,
together with the page scope, buffering information, and the errorPageURL.

By using the pageContext object you can set attributes, get attributes and remove attributes that are
present in the different scopes like as page, request, session, and application scopes which are given
below as follows:

page – Scope: PAGE_CONTEXT

request – Scope: REQUEST_CONTEXT

session – Scope: SESSION_CONTEXT

application – Scope: APPLICATION_CONTEXT

We can disable scripting elements in JSP pages through deployment descriptor configuration like below.

<jsp-config>

<jsp-property-group>

<url-pattern>*.jsp</url-pattern>

<scripting-invalid>true</scripting-invalid>

</jsp-property-group>

</jsp-config>
Above URL-pattern will disable scripting for all the JSP pages but if you want to disable it only for a
specific page, you can give the JSP file name itself.

38. Explain JSP Action Elements or Action Tags?


JSP Action Tags

There are many JSP action tags or elements. Each JSP action tag is used to perform some specific tasks.

The action tags are used to control the flow between pages and to use Java Bean. The Jsp action tags are
given below.

JSP Action Description


Tags

jsp:forward forwards the request and response to another resource.

jsp:include includes another resource.

jsp:useBean creates or locates bean object.

jsp:setProperty sets the value of property in bean object.

jsp:getProperty prints the value of property of the bean.

jsp:plugin embeds another components such as applet.

jsp:param sets the parameter value. It is used in forward and include


mostly.

jsp:fallback can be used to print the message if plugin is working. It is used


in jsp:plugin.

39. What is JSP Expression Language and what are it’s benefits?
The Expression Language (EL) simplifies the accessibility of data stored in the Java Bean component, and
other objects like request, session, application etc.

There are many implicit objects, operators and reserve words in EL.

It is the newly added feature in JSP technology version 2.0.

Syntax for Expression Language (EL)

${ expression }

41. What is JSP Standard Tag Library, provide some example usage?
JSTL stands for JSP Standard Tag Library. JSTL is the standard tag library that provides tags to control the
JSP page behavior. JSTL tags can be used for iteration and control statements, internationalization, SQL
etc. We will look into JSTL Tags in detail in this JSTL tutorial. Earlier we saw how we can use JSP
EL and JSP Action Tags to write JSP code like HTML but their functionality is very limited. For example,
we can’t loop through a collection using EL or action elements and we can’t escape HTML tags to show
them like text in client side. This is where JSTL tags comes handy because we can do much more from
JSTL tags.

Example of JSTL:

The <c:set> Tag with body


variable can be set by using the <c:set> tag within the body of another tag as in the following

code snnipate:

<c:set var="bookname">

My book: java 8

</c:set>

<c:out value="${bookname}"/>

42. How to ignore the EL expression evaluation in a JSP?


We can ignore EL evaluation in JSP page by two ways:

1.Using page directive as <%@ page isELIgnored="true" %>


2.Configuring in web.xml – better approach when you want to disable EL evaluation for many JSP pages.

<jsp-config>

<jsp-property-group>

<url-pattern>*.jsp</url-pattern>

<el-ignored>true</el-ignored>
</jsp-property-group>

</jsp-config>

43. What are the types of JSTL tags?


There are mainly five categories of JSTL tags under the standard tag library of JSP:

1. Core tags: Core tags have variable support, flow control, URL management, etc. The URL
used in the core tag is http://java.sun.com/jsp/jstl/core. These tags are prefixed with a
'c' followed by a colon and then the tag name.
2. Function tags: Function tags holds a collection of standard function. The URL used in this
function tag is http://java.sun.com/jsp/jstl/functions. These tags are prefixed by an 'fn'
followed by a colon.
3. Formatting tags: Formatting tags give support to format the messages, numbers, and
dates, etc. Its URL is http://java.sun.com/jsp/jstl/fmt. It is prefixed with a 'fmt' followed by
a colon.
4. XML tags: XML tags offer a flow control mechanism, transformation, and some other
features. Its URL is http://java.sun.com/jsp/jstl/xml. It is prefixed with a 'x' followed by
a colon.
5. SQL Tags: SQL Tags offers SQL support. The URL is http://java.sun.com/jsp/jstl/sql. It is
prefixed with a 'SQL' followed by a colon.

44. What is JSP Custom Tag and what are its components?

Custom tags are user-defined tags. They eliminates the possibility of scriptlet tag and
separates the business logic from the JSP page.

The same business logic can be used many times by the use of custom tag.

45. Give an example where you need JSP Custom Tag?


In this example, we are going to create a custom tag that prints the current date and time. We are
performing action at the start of tag.

For creating any custom tag, we need to follow following steps:


Create the Tag handler class and perform action at the start or at the end of the tag.

Create the Tag Library Descriptor (TLD) file and define tags

Create the JSP file that uses the Custom tag defined in the TLD file

46. How can we handle exceptions thrown by JSP service method ?


To handle exceptions thrown by the JSP page, all we need is an error page and define the error page in
JSP using page directive.

To create a JSP error page, we need to set page directive attribute isErrorPage value to true, then we
can access exception implicit object in the JSP and use it to send customized error message to the client.

We need to define exception and error handler JSP pages in the deployment descriptor like below:
<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>

<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error.jsp</location>
</error-page>

47. Which JSP lifecycle methods can be overridden?


We can override jspInit() and jspDestroy() methods using JSP declaration scripting element. We should
override jspInit() methods to create common resources that we would like to use in JSP service method
and override jspDestroy() method to release the common resources.

47. How can we prevent implicit session creation in JSP ?


Session object uses the server resources. Each session object uses up a small amount of system
resources as it is stored on the server side. This also increases the traffic as the session ID is sent from
server to client. Client also sends the same session ID along with each request. If some of the JSP pages
on your web site are getting thousands of hits from internet browser and there is not need to identify
the user, so its better to disable the session in that JSP page.

You can tell the container to disable session in the JSP file by setting the session attribute to false. Set
the session attribute of the page directive to false, as shown in the following example:

<%@ page session="false" %>

Here is the full code of jsp file in which session is disabled:


<%@ page language="java" session="false"%>
<html>
<head>
<title>Session Disabled</title>
</head>
<body>
<p>Session is Disabled in this page
</body>
</html>

48. What are the different scope values for the <jsp:useBean> tag?
The JSP useBean action tag is used to locate the bean class is the bean object is instantiated or it
instantiates the bean object. It has many attributes like id, scope, class, type, and beanName. The scope
attribute in the useBean action tag is used to represent the scope of the bean. The default scope is the
page, but different scopes are available such as request, session, and application.

Page – The default scope that specifies the scope of the bean within the JSP page.

Request – specifies the scope of the bean to all the JSP page that processes the same request.

Session – specifies the scope of the bean to all the JSP page that has the same session irrespective of its
request.

Application – specifies the scope of the bean to all the JSP pages in the same application.

50. In JSP page how can we handle runtime exception?

Ans :The Error Page attribute of the page directive can be used to redirects the browser to an error
processing page. When uncaught exception Is encountered

e.g. <%@ page errorPage =”error.jsp”%>

redirects the browser to jsp page error.jsp if an uncaught exception is encountered during the request
processing

In error.jsp if its indirect that its an error processing by <%@page isErrorPage=”true”%>.Directive, then
throwable object describing may be accessed with in the error page via the exception implicit object

You might also like