Nearby lessons
21 of 30JSP - Questions and Answers
- Review JSP fundamentals and lifecycle
- Understand JSP API (JspPage, HttpJspPage)
- Master scripting elements, comments, and implicit objects
- Compare Servlets vs JSP
- Learn best practices for JSP development
Test yourself with the complete JSP Questions and Answers — exam-style Q&A covering JSP fundamentals, lifecycle, API, scripting elements, implicit objects, error handling, directives, and more.
JSP Fundamentals
Q: What is JSP? Describe its concept.
Java Server Pages (JSP) is a server-side component for generating dynamic information as the response. It is best suitable for implementing view components (presentation layer). It is part of SUN's J2EE platform.
Q: What are the benefits of JSP?
- Portability, reusability — logic components can be used across various platforms
- Memory and exception management
- Wide range of API which increases output functionality
- Low maintenance and easy deployment
- Robust performance on multiple requests
Q: Is JSP technology extensible?
Yes. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
Q: Can we implement an interface in a JSP?
No.
Servlets vs JSP
Q: What are the advantages of JSP over Servlet?
- Best suitable for view components
- We can separate presentation and business logic
- The JSP author is not required to have strong Java knowledge
- If we perform changes to the JSP, we don't need to recompile and reload explicitly
- We can reduce development time
Q: What are the differences between Servlets and JSP?
| Servlets | JSP |
|---|---|
| Best suitable for processing logic | Best suitable for presentation logic |
| Cannot separate business logic and presentation logic | Can separate presentation logic and business logic |
| Developer should have strong Java knowledge | Author is not required to have strong Java knowledge |
| For source code changes, we must perform explicit compilation | For source code changes, explicit compilation is not required |
| Relatively more development time | Relatively less development time |
Q: What are the differences between ASP and JSP?
The big difference lies with the design of the software. JSP technology is server and platform independent, whereas ASP relies primarily on Microsoft technologies.
JSP Lifecycle
Q: What are the lifecycle phases of a JSP?
- Page translation — converting from .jsp file to .java file
- Page compilation — converting .java to .class file
- Page loading — the class file is loaded
- Instance creation — an instance of the servlet is created
- jspInit() — called once for initialization
- _jspService() — called for each request
- jspDestroy() — called when the servlet is destroyed
Q: What are the lifecycle methods in JSP?
- jspInit() — called by the container to initialize the servlet instance. Called only once.
- _jspService() — called by the container for each request, passing the request and response objects.
- jspDestroy() — called by the container when it decides to take the instance out of service. It is the last method called.
Q: What is the difference between _jspService() and other lifecycle methods?
JSP contains 3 lifecycle methods: jspInit(), _jspService(), and jspDestroy(). We can override jspInit() and jspDestroy(), but we cannot override _jspService(). The web container generates _jspService() with JSP content. If we write _jspService(), the generated servlet would have two _jspService() methods, causing a compile-time error. The method is prefixed with _ to indicate it should not be overridden.
Q: What is the jspInit() method?
The jspInit() method of the javax.servlet.jsp.JspPage interface is similar to the init() method of servlets. It is invoked by the container only once when a JSP page is initialized. It can be overridden to initialize resources such as database and network connections.
Q: What is the _jspService() method?
The _jspService() method of the javax.servlet.jsp.HttpJspPage interface is invoked every time a new request comes to a JSP page. It takes HttpServletRequest and HttpServletResponse as arguments. A page author cannot override this method — its implementation is provided by the container.
Q: What is the jspDestroy() method?
The jspDestroy() method is invoked by the container when a JSP page is about to be destroyed. It is similar to the destroy() method of servlets. It can be overridden to perform cleanup such as closing database connections.
Q: What JSP lifecycle methods can I override?
We can override jspInit() and jspDestroy(), but we cannot override _jspService().
Q: How can I override the jspInit() and jspDestroy() methods within a JSP page?
By using the JSP declaration tag:
<%!
public void jspInit() {
// ...
}
%>
<%!
public void jspDestroy() {
// ...
}
%>
Q: Explain about translation and execution of Java Server pages.
A Java server page is executed within a Java container. The container converts the JSP into a servlet. Conversion happens only once when the application is deployed. During compilation, the Java compiler checks for modifications — if any are present, it modifies and then executes.
Q: How to pre-compile a JSP?
Add jsp_precompile as a request parameter:
http://localhost:8080/jsp1/test.jsp?jsp_precompile=true
This causes execution of the JSP lifecycle until jspInit() without executing _jspService().
Q: What are the benefits of pre-compiling a JSP page?
It removes the start-up lag that occurs when a container must translate a JSP page upon receipt of the first request.
JSP API
Q: Explain the JSP API.
The JSP API contains only one package: javax.servlet.jsp. It contains 2 interfaces:
1. JspPage — defines the two lifecycle methods jspInit() and jspDestroy().
2. HttpJspPage — defines only one lifecycle method: _jspService(). Every generated servlet for JSPs should implement either JspPage or HttpJspPage directly or indirectly.
Scripting Elements
Q: How many JSP scripting elements are there? Explain them.
Inside JSP, 4 types of scripting elements are allowed:
| Type | Syntax | Purpose |
|---|---|---|
| Scriptlet | <% any java code %> | Place Java code. Placed inside _jspService() method. |
| Declaration | <%! Java declaration %> | Declare class-level variables and methods. Placed at class level in generated servlet. |
| Expression | <%= java expression %> | Print Java expressions. The value becomes argument to out.println(). |
| Comment | <%-- JSP comment --%> | Hidden comment — visible only in the JSP, not in generated servlet or response. |
Q: What is a Scriptlet?
A JSP scriptlet can be used to place Java code. The Java code in the scriptlet is placed directly inside the _jspService() method of the generated servlet.
Q: What is a JSP declaration?
JSP declarations are used to declare class-level variables and methods (both instance and static). These declarations are placed directly at class level in the generated servlet and are available to the entire JSP.
<%! int j = 10; %>
Q: How can I declare methods within my JSP page?
Using the JSP declaration tag:
<%!
public int add(int i, int j) {
return i + j;
}
%>
Q: What is the difference between a variable declared inside a declaration and one declared in a scriptlet?
- Declaration: Variable is treated as an instance variable, placed at class level in the generated servlet:
<%! int k = 10; %> - Scriptlet: Variable is placed inside _jspService() — it acts as a local variable:
<% int k = 10; %>
Q: What is an Expression?
JSP Expression can be used to print an expression to the JSP. The expression should not end with a semicolon. The expression value becomes the argument to out.println() in the generated servlet.
<%= new java.util.Date() %>
JSP Comments
Q: What are the three kinds of comments in JSP?
| Comment Type | Syntax | Visibility |
|---|---|---|
| JSP Comment (hidden) | <%-- this is JSP comment --%> | Visible only in the JSP. Not visible in generated servlet or response. |
| HTML Comment (output) | <!-- this is HTML comment --> | Visible in all phases including the source of the generated response. |
| Java Comment (scripting) | <% // single line /* multi-line */ %> | Visible in the generated servlet. Used within scriptlets only. |
Q: What is an output comment?
The comment which is visible in the source of the response: <!-- this is HTML comment -->
Q: What is a hidden comment?
<%-- this is JSP comment --%> — visible only in the JSP, not in the rest of the JSP lifecycle.
Implicit Objects
Q: What are the JSP implicit objects?
Implicit objects are by default available to every JSP. The JSP author can use them without creating them explicitly.
| Object | Type |
|---|---|
request | HttpServletRequest |
response | HttpServletResponse |
pageContext | PageContext |
session | HttpSession |
application | ServletContext |
out | JspWriter |
config | ServletConfig |
page | Object (the generated servlet instance) |
exception | Throwable (error pages only) |
Q: Is there a way to reference the "this" variable within a JSP page?
Yes. The page implicit object is equivalent to this, and returns a reference to the generated servlet.
Q: Can you make use of a ServletOutputStream object from within a JSP page?
Yes. By using the getOutputStream() method on the response implicit object.
Error Handling
Q: How does JSP handle run-time exceptions?
You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page.
<%@ page errorPage="error.jsp" %>
Within the error page, mark it as an error-processing page:
<%@ page isErrorPage="true" %>
In error pages, the exception implicit object is accessible.
Q: How do you restrict page errors display in the JSP page?
Set the errorPage attribute of the page directive to the error page name, then set isErrorPage="true" in the error page. When an error occurs, control is automatically forwarded to the error page.
JSP Directives
Q: What are the various attributes of the page directive?
The page directive contains 13 attributes:
language, extends, import, session, isThreadSafe, info,
errorPage, isErrorPage, contentType, isELIgnored,
buffer, autoFlush, pageEncoding
Q: How is scripting disabled?
By setting the scripting-invalid element of the deployment descriptor to true:
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
Q: Explain about autoFlush?
The autoFlush attribute controls buffer flushing. If true, the buffer is flushed whenever it is full. If false, an exception is thrown when the buffer is full.
Q: Can we stop JSP execution while in the midst of processing a request?
Yes. Preemptive termination of request processing on an error condition maximizes throughput. Use the return statement when you want to terminate further processing.
Protecting JSP Pages
Q: How to protect JSPs from direct access?
If the JSP is a secured resource, place it inside the WEB-INF folder so that end users cannot access it directly by name. Configure the URL pattern in web.xml:
<web-app>
<servlet>
<servlet-name>Demo JSP</servlet-name>
<jsp-file>/WEB-INF/test.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>Demo JSP</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
Thread Safety
Q: How can I implement a thread-safe JSP page? What are the advantages and disadvantages?
You can make JSPs thread-safe by having them implement the SingleThreadModel interface:
<%@ page isThreadSafe="false" %>
The generated servlet handles only one client request at a time, overcoming data inconsistency problems.
Advantage: Thread safety, data consistency.
Disadvantage: May affect system performance.
Q: What is a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel or synchronization?
The synchronized keyword is recommended for thread safety, rather than SingleThreadModel.
Scopes
Q: What are the different scopes available for JSPs?
| Scope | Description |
|---|---|
page | Available within the same page only |
request | Available after forward or include as well |
session | Available after sendRedirect. Data persists until session closes or browser closes. |
application | Available throughout the application. One user can store data, other users can access it. |
Q: When do we use application scope?
When we want to make data available to the entire application — across all users and sessions.
Q: What are the different scope values for jsp:useBean?
page, request, session, application.
Include Directive vs Action
Q: How do we include static files within a JSP page?
By using the include directive (static include):
<%@ include file="header.jsp" %>
The content of header.jsp is included at translation time.
Q: In JSP, how many ways are there to perform inclusion?
4 ways:
- Include directive:
<%@ include file="header.jsp" %>— translation time (static) - Include action:
<jsp:include page="header.jsp" />— runtime (dynamic) - pageContext.include():
pageContext.include("/header.jsp");— runtime - RequestDispatcher:
request.getRequestDispatcher("/header.jsp").include(request, response);— runtime
Q: When should we use static include vs dynamic include?
- If the target resource won't change frequently → use static include
- If the target resource will change frequently → use dynamic include
Beans in JSP
Q: How do I use a scriptlet to initialize a newly instantiated bean?
The jsp:useBean action may optionally have a body. If specified, its contents are automatically invoked when the bean is instantiated:
<jsp:useBean id="foo" class="com.Bar.Foo">
<jsp:setProperty name="foo" property="today"
value="<%= java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>" />
</jsp:useBean>
Q: Can a JSP page instantiate a serialized bean?
Yes. Use the beanName attribute to indicate a serialized bean. The serialized file must be named filename.ser and placed in the WEB-INF/jspbeans directory.
ServletContext vs PageContext
Q: What is the difference between ServletContext and PageContext?
- ServletContext: Gives information about the container and represents an application.
- PageContext: Gives information about the Request and can provide all other implicit JSP objects.
- Comprehensive Q&A covering all JSP topics
- Exam-style questions with clear answers
- Quick reference for JSP interview preparation