Nearby lessons

30 of 30

JSP Examples - Revision & QA

📌 What You Will Learn
  • Revise the JSP life cycle step by step
  • Deep-dive the HttpJspPage interface
  • Review comment types and include mechanisms

Exam-style revision material: JSP life cycle Q&A, the HttpJspPage interface in depth, Java comments vs JSP comments, and include-by-action programs — perfect for last-minute review.

3) Explain about Life Cycle of JSP

Java Server Pages (JSP) is a server side component for the generation of dynamic

information as the response. Best suitable to implement view components (presentation

layer components). It is part of SUN's J2EE platform.

Example01
JCode Cell
1 
2What is JSP ? Describe its Concept?
3

3) Explain about Life Cycle of JSP

These are some of the benefits due to the usage of JSP they are:

Example02
JCode Cell
1 
2Explain the benefits of JSP?
3

3) Explain about Life Cycle of JSP

Yes, it is. JSP technology is extensible through the development of custom actions, or tags,

which are encapsulated in tag libraries.

Example03
JCode Cell
1 
2Portability, reusability and logic components of the language can be used across variousplatforms.
3Memory and exception management.
4Has wide range of API which increases the output functionality.
5Low maintenance and easy deployment.
6Robust performance on multiple requests.
7Is JSP technology extensible?
8

3) Explain about Life Cycle of JSP

ServletsJSP
1) Best suitable for processing Logic1) Best suitable for presentation Logic
Example04
JCode Cell
1 
2Can we implement an interface in a JSP?No
3What are the advantages of JSP over Servlet?
4Best suitable for view components
5We can separate presentation and business logic
6The JSP author not required to have strong java knowledge
7If we are performing any changes to the JSP, then not required to recompile andreload explicitly
8We can reduce development time.
9Differences between Servlets and JSP?
10

3) Explain about Life Cycle of JSP

Presentation LogicBusiness Logic is possible
3) Servlet Developer should have Strong3) JSP Author is not required to have Strong
Knowledge in JavaKnowledge in Java
4) For Source Code changes ,we have to4) For Source Code changes ,it is not
perform explicitly Compilationrequired to perform explicit Compilation
5) Relatively Development Time is more5) Relatively Development Time is less
Example05
JCode Cell
1 
2We cannot separate Business Logic and 2) Separation of Presentation Logic and
3

3) Explain about Life Cycle of JSP

The big difference between both of these technologies lies with the design of the software.

JSP technology is server and platform independent whereas ASP relies primarily on

Microsoft technologies.

Example06
JCode Cell
1 
2Explain the differences between ASP and JSP?
3

3) Explain about Life Cycle of JSP

Yes. Preemptive termination of request processing on an error condition is a good way to

maximize the throughput of a high-volume JSP engine. The trick (assuming Java is your

scripting language) is to use the return statement when we want to terminate further

processing.

Example07
JCode Cell
1 
2Can I stop JSP execution while in the midst of processing a request?
3

3) Explain about Life Cycle of JSP

If the JSP is secured resource then we can place inside WEB-INF folder so that end user is

not allowed to access directly by the name. We can provide the url pattern by configuring in

web.xml

Example08
JCode Cell
1 
2How to Protect JSPs from direct access ?
3

3) Explain about Life Cycle of JSP

The JSP API contains only one package : javax.servlet.jsp

It contains the following 2 interfaces:

Example09
JCode Cell
1 
2<web-app>
3<servlet>
4<servlet-name>Demo JSP</servlet-name>
5<jsp-file>/WEB-INF/test.jsp</jsp-file>
6<sevlet>
7<servlet-mapping>
8<servlet-name>Demo JSP</servlet-name>
9<url-pattern>/test</url-pattern>
10</servlet-mapping>
11..
12</web-app>
13Explain JSP API ?
14

2) HttpJspPage

Life cycle of JSP contains the following phases:

Page translation: -converting from .jsp file to .java file

Page compilation: converting .java to .class file

Page loading : This class file is loaded.

Create an instance :- Instance of servlet is created

jspInit() method is called

_jspService() is called to handle service calls

jspDestroy() is called to destroy it when the servlet is not required.

Example10
JCode Cell
1 
2What are the lifecycle phases of a JSP?
3

2) HttpJspPage

The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called

before any other method, and is called only once for a servlet instance.

The _jspservice()- The container calls the _jspservice() for each request, passing it the

request and the response objects.

The jspDestroy()- The container calls this when it decides take the instance out of service. It

is the last method called n the servlet instance.

Example11
JCode Cell
1 
2Explain the life-cycle mehtods in JSP?
3

2) HttpJspPage

JSP contains 3 life cycle methods namely jspInit( ), _jspService() and jspDestroy().

In these, jspInit() and jspDestroy() can be overridden and we cannot override _jspService().

Webcontainer always generate _jspService() method with JSP content. If we are writing

_jspService() method , then generated servlet contains 2 _jspService() methods which will

cause compile time error.

To show this difference _jspService() method is prefixed with `_' by the JSP container and

the other two methods jspInit() and jspDestroy() has no special prefixes.

Example12
JCode Cell
1 
2Difference between _jspService() and other life cycle methods.
3

2) HttpJspPage

The jspInit() method of the javax.servlet.jsp.JspPage interface is similar to the init() method

of servlets. This method is invoked by the container only once when a JSP page is initialized.

It can be overridden by a page author to initialize resources such as database and network

connections, and to allow a JSP page to read persistent configuration data.

Example13
JCode Cell
1 
2What is the jspInit() method?
3

2) HttpJspPage

The _jspService() method of the javax.servlet.jsp.HttpJspPage interface is invoked every

time a new request comes to a JSP page. This method takes the HttpServletRequest and

HttpServletResponse objects as its arguments. A page author cannot override this method, as

its implementation is provided by the container.

Example14
JCode Cell
1 
2What is the _jspService() method?
3

2) HttpJspPage

The jspDestroy() method of the javax.servlet.jsp.JspPage interface is invoked by the

container when a JSP page is about to be destroyed. This method is similar to the destroy()

method of servlets. It can be overridden by a page author to perform any cleanup operation

such as closing a database connection.

Example15
JCode Cell
1 
2What is the jspDestroy() method?
3

2) HttpJspPage

We can override jspInit() and jspDestroy() methods but we cannot override _jspService()

method.

Example16
JCode Cell
1 
2What JSP lifecycle methods can I override?
3

2) HttpJspPage

By using JSP declation tag

Example17
JCode Cell
1 
2How can I override the jspInit() and jspDestroy() methods within a JSP page?
3

2) HttpJspPage

A java server page is executed within a Java container. A Java container converts a Java file

into a servlet. Conversion happens only once when the application is deployed onto the web

server. During the process of compilation Java compiler checks for modifications if any

modifications are present it would modify and then execute it.

Example18
JCode Cell
1 
2<%!
3public void jspInit() {
4. . .
5}
6%>
7<%!
8public void jspDestroy() {
9. . .
10}
11%>
12Explain about translation and execution of Java Server pages?
13

2) HttpJspPage

_jspService() method will be written by the container hence any methods which are not to be

overridden by the end user are typically written starting with an '_'. This is the reason why we

don't override _jspService() method in any JSP page.

Example19
JCode Cell
1 
2Why is _jspService() method starting with an '_' while other life cycle methods do not?
3

2) HttpJspPage

Add jsp_precompile as a request parameter and send a request to the JSP file. This will

make the jsp pre-compile.

http://localhost:8080/jsp1/test.jsp?jsp_precompile=true

It causes excution of JSP life cycle until jspInit() method without executing _jspService()

method.

Example20
JCode Cell
1 
2How to pre-compile JSP?
3

2) HttpJspPage

It removes the start-up lag that occurs when a container must translate a JSP page upon

receipt of the first request.

Example21
JCode Cell
1 
2The benefits of pre-compiling a JSP page?
3

2) HttpJspPage

Inside JSP 4 types of scripting elements are allowed.

Example22
JCode Cell
1 
2How many JSP scripting elements and explain them?
3

2) HttpJspPage

Can be used to place java code.

Example23
JCode Cell
1 
2Scriptlet <% any java code %>
3

2) HttpJspPage

Can be used to declare class level variables and methods

Example24
JCode Cell
1 
2declarative <%! Java declaration %>
3

2) HttpJspPage

To print java expressions in the JSP

Example25
JCode Cell
1 
2expression: <%= java expression %>
3

2) HttpJspPage

JSP scriptlet can be used to place java code.

Syntax:

<%

Any java code

%>

The java code present in the scriptlet will be placed directly inside _jspService() method

Example26
JCode Cell
1 
2comment <%-- jsp comment --%>
3What is a Scriptlet?
4

2) HttpJspPage

JSP declarations are used to declare class variables and methods (both instance and static) in

a JSP page. These declations will be placed directly at class level in the generated servlet and

these are available to the entire JSP.

Syntax:

<%! This is my declarative %>

Eg: <%! int j = 10; %>

Example27
JCode Cell
1 
2What is a JSP declarative?
3

2) HttpJspPage

We can declare methods by using JSP declarative tag.

<%!

public int add(inti, intj) {

return i+j;

}

%>

Example28
JCode Cell
1 
2How can I declare methods within my JSP page?
3

2) HttpJspPage

declared in scriplet ?

Variable declared inside declaration part is treated as a instance variable and will be placed

directly at class level in the generated servlet.

<%! int k = 10; %>

Variable declared in a scriptlet will be placed inside _jspService() method of generated

servlet.It acts as local variable.

<%

int k = 10;

%>

Example29
JCode Cell
1 
2What is the difference b/w variable declared inside a declaration and variable
3

2) HttpJspPage

JSP Expression can be used to print expression to the JSP.

Syntax:

<%= java expression %>

Eg: <%= new java.util.Date() %>

The expression in expression tag should not ends with semi-colon

The expression value will become argument to the out.pritln() method in the generated

servlet

Example30
JCode Cell
1 
2What is a Expression?
3

2) HttpJspPage

3 types of comments are allowed in JSP

Example31
JCode Cell
1 
2What are the three kinds of comments in JSP and what's the difference betweenthem?
3

Java Comments

The comment which is visible in the source of the response is called output comment.

<!-- this is HTMl comment -- >

Example32
JCode Cell
1 
2What is output comment?
3

Java Comments

<%-- this is jsp comment --%>

This is also known as JSP comment and it is visible only in the JSP and in rest of phases of

JSP life cycle it is not visible.

Example33
JCode Cell
1 
2What is a Hidden Comment?
3

Java Comments

Scripting is disabled by setting the scripting-invalid element of the deployment descriptor to

true. It is a subelement of jsp-property-group. Its valid values are true and false. The syntax

for disabling scripting is as follows:

<jsp-property-group>

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

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

</jsp-property-group>

Example34
JCode Cell
1 
2How is scripting disabled?
3

Java Comments

Implicit objects are by default available to the JSP. Being JSP author we can use these and

not required to create it explicitly.

Example35
JCode Cell
1 
2What are the JSP implicit objects?
3

Java Comments

You can use the errorPage attribute of the page directive to have uncaught run-time

exceptions automatically forwarded to an error processing page.

For example:

<%@ page errorPage="error.jsp" %> redirects the browser to the JSP page error.jsp if an

uncaught exception is encountered during request processing.

Within error.jsp, if you indicate that it is an error-processing page, via the directive:

<%@ page isErrorPage="true" %>

In the error pages we can access exception implicit object.

Example36
JCode Cell
1 
2request
3response
4pageContext
5session
6application
7out
8config
9page
10exception
11How does JSP handle run-time exceptions?
12

Java Comments

Disadvantages of using it?

You can make your JSPs thread-safe by having them implement the

SingleThreadModel interface. This is done by adding the directive in the JSP.

<%@ page isThreadSafe="false" %>

The generated servlet can handle only one client request at time so that we can make JSP as

thread safe. We can overcome data inconsistency problems by this approach.

The main limitation is it may affect the performance of the system.

Example37
JCode Cell
1 
2How can I implement a thread-safe JSP page? What are the advantages and
3

Java Comments

ServletContext: Gives the information about the container and it represents an application.

PageContext: Gives the information about the Request and it can provide all other implicit

JSP objects .

Example38
JCode Cell
1 
2What is the difference between ServletContext and PageContext?
3

Java Comments

Yes, there is. The page implicit object is equivalent to "this", and returns a reference to the

generated servlet.

Example39
JCode Cell
1 
2Is there a way to reference the "this" variable within a JSP page?
3

Java Comments

Yes . By using getOutputStream() method on response implicit object we can get it.

Example40
JCode Cell
1 
2Can you make use of a ServletOutputStream object from within a JSP page?
3

Java Comments

session object is by default available to the JSP. We can make it unavailable by using page

directive as follows.

<%@ page session="false">

Example41
JCode Cell
1 
2What is the page directive is used to prevent a JSP page from automatically creatinga session?
3

Java Comments

Model Interface OR Synchronization?

Synchronized keyword is recommended to use to get thread-safety.

Example42
JCode Cell
1 
2What's a better approach for enabling thread-safe servlets and JSPs? Single Thread
3

Java Comments

Page directive contains the following 13 attributes.

Example43
JCode Cell
1 
2What are various attributes Of Page Directive?
3

Java Comments

This command is used to autoflush the contents. If a value of true is used it indicates to flush

the buffer whenever it is full. In case of false it indicates that an exception should be thrown

whenever the buffer is full. If you are trying to access the page at the time of conversion of a

JSP into servlet will result in error.

Example44
JCode Cell
1 
2language
3extends
4import
5session
6isThreadSafe
7info
8errorPage
9isError page
10contentType
11isELIgnored
12buffer
13autoFlush
14pageEncoding
15Explain about autoflush?
16

Java Comments

You first set "errorPage" attribute of PAGE directive to the name of the error page (ie

errorPage="error.jsp")in your jsp page .

Then in the error.jsp page set "isErrorpage=TRUE".

When an error occur in your jsp page, then the control will be automatically forward to error

page.

Example45
JCode Cell
1 
2How do you restrict page errors display in the JSP page?
3

Java Comments

There are 4 types of scopes are allowed in the JSP.

Example46
JCode Cell
1 
2What are the different scopes available fos JSPs ?
3

Java Comments

session is available to end user till session closed or browser closed.

Example47
JCode Cell
1 
2page - with in the same page
3request - after forward or include also you will get the request scope data.
4session - after senRedirect also you will get the session scope data. All data stored in
5

Java Comments

in application scope and other can get the data from application scope.

Example48
JCode Cell
1 
2application - Data will be available throughout the application. One user can store data
3

Java Comments

If we want to make our data available to the entire application then we have to use

application scope.

Example49
JCode Cell
1 
2When do use application scope?
3

Java Comments

The different scope values for <jsp:useBean> are

Example50
JCode Cell
1 
2What are the different scope valiues for the <jsp:useBean>?
3

Java Comments

jsp:useBean action may optionally have a body. If the body is specified, its contents will be

automatically invoked when the specified bean is instantiated. Typically, the body will

contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although

you are not restricted to using those alone.

The following example shows the "today" property of the Foo bean initialized to the current

date when it is instantiated. Note that here, we make use of a JSP expression within the

jsp:setProperty action.

<jsp:useBean id="foo" class="com.Bar.Foo" >

<jsp:setProperty name="foo" property="x"

value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>" / >

<%-- scriptlets calling bean setter methods go here --%>

</jsp:useBean >

Example51
JCode Cell
1 
2page
3request
4session
5application
6How do I use a scriptlet to initialize a newly instantiated bean?
7

Java Comments

No problem! The use Bean action specifies the beanName attribute, which can be used for

indicating a serialized bean.

For example:

A couple of important points to note. Although you would have to name your serialized file

"filename.ser", you only indicate "filename" as the value for the beanName attribute. Also,

you will have to place your serialized file within the WEB-INF/jspbeans directory for it to be

located by the JSP engine.

Example52
JCode Cell
1 
2Can a JSP page instantiate a serialized bean?
3

Java Comments

We can include static files in JSP by using include directive (static include)

<%@ include file="header.jsp" %>

The content of the header.jsp will be included in the current jsp at translation time. Hence

this inclusion is also known as static include.

Example53
JCode Cell
1 
2How do we include static files within a jsp page ?
3

Java Comments

In JSP, we can perform inclusion in the following ways.

Example54
JCode Cell
1 
2In JSPs how many ways are possible to perform inclusion?
3

2) By include action

pageContext.include("/header.jsp");

%>

This inclusion also happened at request processing time(run time).

Example55
JCode Cell
1 
2By using pageContext implicit object<%
3

2) By include action

RequestDispatcher rd = request.getRequestDispatcher("/header.jsp");

Rd.incliude(request,response);

%>

Example56
JCode Cell
1 
2By using RequestDispatcher object<%
3

2) By include action

If the target resource ( included resource) won't change frequently, then it is recommended to

use static include.

<%@ include file="header.jsp" %>

If the target resource(Included page) will change frequently , then it is recommended to use

dynamic include.

< jsp:include page="header.jsp" />

OCWCD

Question Bank

Example57
JCode Cell
1 
2In which situation we can use static include and dynamic include in JSPs?
3
📝 Key Takeaways
  • Life cycle: translate, compile, load, instantiate, jspInit, _jspService, jspDestroy
  • _jspService is auto-generated — never write it
  • Three comment types: JSP (hidden), HTML (visible), Java (servlet-only)