Professional Documents
Culture Documents
JSP SPD Answer
JSP SPD Answer
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.
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.
Database: It is used to store the user’s data. The webserver has access to the database.
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.
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.
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().
Syntax:
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: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.
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.
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.
config ServletConfig This is the ServletConfig object associated with the page.
session HttpSession This is the HttpSession object associated with the request.
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.
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.
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.
Events that occur when the mouse interacts with the HTML document belongs to the MouseEvent
Object.
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
ctrlKey Returns whether the "CTRL" key was pressed when the mouse
event was triggered
metaKey Returns whether the "META" key was pressed when an event
was triggered
region
relatedTarget Returns the element related to the element that triggered the
mouse event
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
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.
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.
5) Get request is more efficient and used more than Post. Post request is less efficient and used less than
get.
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.
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
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.
• 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.
You can make a cookie by calling the cookie constructor with the cookie value and name, both of which
are strings.
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:
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
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.
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.
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
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.
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>
Comments are also helpful in debugging the code, because we can comment out the lines of code to
search for errors.
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:
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 :
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.
/*
Multiline comment
*/
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:
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.
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.
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.
${ 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:
code snnipate:
<c:set var="bookname">
My book: java 8
</c:set>
<c:out value="${bookname}"/>
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<el-ignored>true</el-ignored>
</jsp-property-group>
</jsp-config>
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.
Create the Tag Library Descriptor (TLD) file and define tags
Create the JSP file that uses the Custom tag defined in the TLD file
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>
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:
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.
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
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