Greetings readers, we’ve prepared the list of 50 most frequently asked JSP interview questions that can help you greatly in getting a lead during any Java/J2EE interview.
The idea we thought was to wear the shoes of the interviewer and come up with straight JSP interview questions to ask our readers.
JSP is an integral part of any Java EE web application, and we’ve covered the basics of JSP, JSP scripting, custom JSP tags, etc. in this post. If you keenly want to evaluate your existing JSP/J2EE knowledge, then try your hands on this excellent JSP quiz we recently published.
However, if you wish to refer to an online tutorial on the subject, we recommend peeking into Oracle’s documentation. Let’s now dig into the well of the most technical JSP interview questions and answers.
Basic Concept-Related JSP Interview Questions
In this basic JSP interview section, you’ll find questions covering the basics of JSP, such as its lifecycle, syntax, and tags.
Must Read: 20 Spring Boot Interview Questions and Answers
1- What is JSP technology and what is its purpose?
JSP, also known as Java Server Pages, is a versatile cross-platform technology that operates within the presentation layer and is a part of the J2EE platform. JSPs resemble standard HTML web pages, but they contain embedded Java code.
These JSP files typically carry the *.jsp file extension. The J2EE platform includes a JSP compiler that generates a Servlet class based on the content of the JSP page.
JSP technology enables web developers to add Java code and some predefined actions to the static content. A Java server page converts into a Java servlet by the JSP compiler.
2- How does a servlet differ from the JSP?
The JSP and Servlets are both web components and their basic functions are similar. However, a JSP finally ends up being a servlet at run-time. The main variation between the two is that JSPs are useful for operations that are HTML-intensive whereas a Servlet works best for tasks that are Java-intensive. The below example can elaborate on the difference.
Example: A web application that follows the MVC model separates the components into three groups.
- Model- Represents the modules that contain application data e.g. Java beans.
- View- It is the part of the application that displays information. e.g. dynamically generated HTML, JSP handles this part very well.
- Controller- Its job is to work as a carrier between the model and the view. The controller places the user-entered information into the model and forwards it to the next view. Servlets fulfill this purpose perfectly.
3- What are the advantages of JSP over Servlet?
JSP is a server-side construct to simplify the dynamic generation of HTML content. One of its advantages is that JSP is document-centric. While the Servlets purely behave like the programs. A JSP Page can consist of Java code fragments that can instantiate and invoke the methods of Java classes. All of this occurs inside an HTML template file whose purpose is to generate dynamic content. However, some of the JSP functionality can be achieved at the client end using JavaScript. The power of JSP is that it runs on the server side and provides a framework for Web applications.
Advantages of JSP.
- JSP represents an HTML page embedded with Java code.
- JSP is a cross-platform technology.
- JSP can create database-driven Web applications.
- JSP enables Server-side programming abilities.
4- What are the JSP lifecycle phases?
Upon the initial request for a JSP page, the servlet container generates and loads the required servlet code. Subsequently, the servlet code actively manages incoming requests from the browser while the JSP page is being fully rendered. If there are any changes in the JSP page, the JSP compiler promptly regenerates the servlet code, ensuring synchronization with the updated page structure. This dynamic and responsive interaction between the JSP page, servlet code, and compiler facilitates smooth and efficient web application behavior.
Let’s now dig into the different JSP lifecycle phases:
- Translation – The JSP container verifies the JSP page code and parses it to generate the servlet source code.
- Compilation – The JSP container compiles the JSP page and creates a class file in this phase.
- Class Loading – At this stage, the container reads the JSP class into application memory.
- Instantiation – This phase guides the container to execute the no-args constructor of the generated JSP class.
- Initialization – The container calls the JSP class init method and initializes the servlet config.
- Request Processing – This is the phase where the JSP page creates threads to process a request.
- Destroy – This is the terminal phase of the JSP life cycle where the JSP class unloads itself from the memory.
5- What are JSP lifecycle methods?
- The JSP container executes the jspInit() method the first time it initializes the JSP.
- Whenever the container receives a request, it invokes the _jspService() method, processes the request, and generates a response.
- The container calls the jspDestroy() method for cleaning up the memory allocated for the JSP.
6- Which of the JSP life cycle methods you can override?
You can’t override the _jspService() Method within a JSP page. However, there are two approaches you can take to override the jspInit() and jspDestroy() methods within the JSP page.
jspInit() Can be quite useful for reserving resources like DB connections, N/W connections, and so forth for the JSP page. It is a good programming practice to free any allocated resources in the jspDestroy() method.
A bit more advanced JSP interview questions and answers would include topics, such as custom JSP tags, implicit objects, and beans.
7- What are your thoughts on the implicit JSP objects?
Implicit objects in JSP are like shortcuts that can make your code easier to write and read. They give you access to common objects, such as the request, response, and session, without having to write extra code.
For example, instead of writing the following code to get the request parameter “name”:
String name = request.getParameter("name");
You can use the name
implicit object to get the parameter directly:
String name = name;
This is a simple example, but it shows how implicit objects can save you time and effort when writing JSP code. Here is a table of the most common implicit objects in JSP:
Implicit Object | Description |
---|---|
#1_request | Provides access to the HTTP request. |
#2_response | Provides access to the HTTP response. |
#3_pageContext | Provides access to the current JSP page context. |
#4_session | Provides access to the HTTP session. |
#5_application | Provides access to the ServletContext object. |
#6_out | Provides access to the JspWriter object. |
#7_config | Provides access to the ServletConfig object. |
#8_page | Provides access to the current JSP page. |
8- What are the different types of JSP tags?
The various types of JSP tags are as follows:
9- What purpose does Standard Tag Library a.k.a. JSTL serve?
JSTL eases up JSP development by providing custom tags for tasks like conditional logic, looping, variable handling, and text formatting. It improves code readability and separation of concerns in JSP apps.
Here are core tag examples:
<c:out>
: Displays variable values.<c:out value="${user.name}" />
<c:set>
: Sets variables.<c:set var="total" value="${price * quantity}" />
<c:if>
: Conditional rendering.<c:if test="${condition}"> ... </c:if>
10- How many types of tags exist in the JSTL library?
Looking at the functions JSTL has, there are five types of JSTL tags that we should know.
- Core Tags – Enable support for loops, conditional logic, exception handling, the ability to forward/redirect responses, etc.
- Formatting/Localization Tags – add features like the manipulation of date/number format and enabling i18n support with the help of localization packages.
- JSTL Functions Tags – JSTL has a set of features that allow String handling features like concatenation, split operations, etc.
- XML Tags – Enables the reading/writing of XML documents. Some of the key features are XML parsing, processing XML, and evaluation of XPath expressions.
- SQL Tags – JSTL brings some unique tags that cater to the integration of JSP pages with databases like MySql, Oracle, etc.
Intermediate level JSP Interview Questions & Answers.
11- What is the function of Custom Tags in JSP and what do they include?
Custom tags in JSP are used to extend the functionality of the standard JSP tags. We can create Custom Tags in JSP with the below elements:
- Custom tags are defined using a Java class called a tag handler. The tag handler implements the logic of the tag and is responsible for generating the output of the tag.
- To use a custom tag in a JSP page, you must first define the tag library in the JSP page’s TLD file. The TLD file contains information about the tag, such as its name, attributes, and tag handler class.
- Once the tag library has been defined, you can use the custom tag in your JSP page by simply adding the tag to the page. The JSP engine will then invoke the tag handler to generate the output of the tag.
12- When should you use a Custom Tag in JSP?
You should use a custom tag in JSP when you need to perform a task that is not possible with the standard JSP tags. For example, you might use a custom tag to:
- Encapsulate common JSP code into a reusable component. This can make your code more modular and easier to maintain.
- Implement custom business logic. For example, you might use a custom tag to validate user input or to perform complex calculations.
- Interact with external resources, such as databases and web services.
- Generate dynamic content, such as menus and navigation bars.
13- Why is it not mandatory to configure the standard JSP tags in the web.xml?
This is because the JSP engine automatically recognized the standard tags. The primary work of a JSP engine is to process the JSP pages. The web server sends the page to the JSP engine which then produces a servlet and executes it.
There is only a case when we need JSP tags to set in the web.xml is when using a custom a custom tag library. Otherwise, you can deploy your JSP application without having to modify the web.xml file.
Not configuring the standard JSP tags in the web.xml has several benefits:
– Reduced configuration
– Simplified deployment
– Improved portability
Overall, it is generally recommended not to configure the standard JSP tags in the web.xml. However, there are some cases where you may need to do so.
14- How do you manage if the JSP service handler throws an exception?
The best approach for managing the exception on a JSP page is by defining the error page using the page directive.
You can quickly add a JSP error page by following the below steps:
a) Define an error page in your web.xml:
<error-page> <exception-type>java.lang.Exception</exception-type> <location>/error.jsp</location> </error-page>
In this example, if a java.lang.Exception
is thrown, the application will redirect to the error.jsp
page.
b) Create the error.jsp
page to process the exception:
Refer to the example given below.
<%@ page isErrorPage="true" %> <html> <head> <title>Error Page</title> </head> <body> <h1>An error occurred:</h1> <p><%= exception.getMessage() %></p> </body> </html>
The isErrorPage="true"
ensures the JSP page can access the exception instance, and we can set a custom error message
15- How to deal with exceptions using the JSTL library?
JSTL has core tags like the <c: catch> and <c: if> to handle exceptions within the JSP service code. The <c: catch> tag grabs the exception and saves it to an exception variable which you can process later using the <c: if> condition tag.
Refer to the code fragment given below.
<c:catch var ="ex"> <% int result = 99/0;%> </c:catch> <c:if test = "${ex ne null}"> <p>Following exception occured : ${ex} <br /> Error Message: ${ex.message}</p> </c:if>
We’ve used the JSP EL (JavaServer Pages Expression Language) in the <c: if> condition of the above example.
16- What are the different JSP scripting elements?
There are three types of scripting language elements:
- Declarations,
- Scriptlets, and
- Expressions.
There are JSP interview questions and answers on the development best practices, such as how to write efficient and maintainable JSP code.
17- What is the logic behind a scriptlet in JSP?
A scriptlet holds the executable Java code which runs whenever the JSP gets loaded. The scriptlet passes its code to the service() method while the JSP is getting compiled to a servlet. So all the scriptlet variables and methods become local to the service() method. A scriptlet is coded between the <% and %> tags and the container calls it while processing the request.
18- What is a JSP declaration?
JSP Declarations help to declare the class variables and methods on a JSP page. They get initialized along with the initialization of the class. Everything in a <declaration> is accessible to the whole JSP page. You can encircle a declaration block within the <%! And %> tags.
19- What is a JSP expression?
A JSP expression helps to write an output without using the <out.print statement>
. You can see it as a shorthand description for the scriptlets. And as usual, you delimit an expression using the <%= and %> tags.
Ending the expression with a semicolon is not mandatory, as it gets automatically added to the <expressions> within the expression tags.
20- What do you understand of the JSP directives?
- JSP directives are the instructions for the JSP container to control the processing of the whole page.
- They add the ability to set global values such as a class declaration, method definition, output data type, etc.
- They don’t send any output to the client.
- All directives should get enclosed within <%@ %> tag.
e.g. page and include directive, etc.
21-What do you understand of the page directive?
- It notifies the JSP container of the headers (facilities) that the page receives from the environment.
- Usually, the page directive remains at the top of a JSP page.
- A JSP page can have any number of page directives if the attribute–value pair is unique.
- The include directive syntax is: <%@ page attribute=”value”>
// E.g. <%@ include file="header.jsp" %>
22- Explain the different attributes of a page directive.
There are about 13 attributes available for a page directive. Some of the important ones are as follows:
- <import>: Signifies the packages that get queued for import.
- <session>: Specifies the session data available on the JSP page.
- <contentType>: Allows a user to update the content type for a page.
- <isELIgnored>: Specifies if an EL expression gets ignored during the translation of the JSP to a servlet.
23- What is the included directive?
Its purpose is to attach the static resources to the current JSP page during the translation process. The included directive syntax is as follows:
// JSP include directive syntax <%@ include file = "File-Name" %>
- The include directive statically embeds the contents of a resource into the current JSP.
- It allows a user to reuse the code without duplicating it and inserts the data of the target file during JSP translation.
- This directive has only one attribute called <file> that specifies the name of the file to include.
24- What is the significance of the JSP standard actions and what is their purpose?
- The standard actions in JSP not only control the runtime behavior of the JSP page, but they do affect the response posted back to the client side.
- We use them for the following purposes.
- Include a file at the requested time,
- Locate or instantiate a JavaBean,
- Forward a request to a new page, or
- Generate a browser-specific code, etc.
- Some of them can be seen in the below example.
// E.g. include, param, useBean, etc.
25- What are the standard actions available in JSP?
Please refer to the below list:
- <jsp: include>: Used to specify a response from the servlet or a JSP page into the current page.
- <jsp: forward>: Used to send a reply from the servlet/JSP page to another page.
- <jsp: useBean>: Allows a JavaBean to get accessible from a page and initializes the bean.
- <jsp: setProperty>: Used to set the JavaBean properties.
- <jsp: getProperty>: Fetches the property value from a JavaBean component and appends it to the response.
- <jsp: param>: Used with actions like <jsp:forward> and <jsp:, or plugin> to append a parameter to the request.
- <jsp: plugin>: Specifies whether to add a Java applet or a JavaBean to the current JSP page.
26- What is the purpose of the <jsp: useBean> action?
The <jsp: useBean> standard action allows us to identify an existing JavaBean or to create one if it doesn’t exist.
It contains attributes to classify the object instance, to specify the lifetime of the bean, as well as the fully qualified classpath and type.
27- Define the scopes available with the <jsp: useBean>.
- Page Scope: This tells the bean object is available for the entire JSP page without any external access.
- Request Scope: This signifies the object can link with a particular request and persist till the time request lasts.
- Session Scope: States that the bean object is available throughout the session.
- Application Scope: Specifies the bean object is available throughout the entire Web application discarding any external access.
In addition to the above JSP interview questions, the interviewer may ask you more specific questions about the web applications/projects that you have worked on.
28- What is the purpose of the <jsp: forward> action?
- The <jsp: forward> standard action forwards a response from a servlet or a JSP page to another page.
- The execution of the current page gets stopped, and control shifts to the forwarded page.
- The <jsp: forward> standard action uses the below syntax.
// JSP forward syntax <jsp:forward page="/targetPageTemplate" />
Here, targetPage could either be a JSP/HTML page, or a servlet within the same context.
- If anything gets written to the output stream but not buffered before the <jsp: forward>, it’ll result in an IllegalStateException.
Note: Before you use <jsp: forward> or <jsp: include> in a page, make sure the buffering is on. However, the buffer is enabled by default.
29- What is the purpose of the <jsp: include> standard action?
The <jsp: include> standard action instructs the JSP page to include a static/dynamic resource at run-time. Unlike the include directive, the include action is best suited for resources that undergo frequent changes. The resources you wish to add must be in the same context. The syntax of the <jsp: include> standard action is as follows:
// JSP include syntax <jsp:include page="targetPage" flush="true"/>
Here, the <targetPage> is the page to be included in the current JSP page.
30- Explain the main differences between an include action and the include directive.
- The include directive adds the target content during the translation phase while the page is compiled to a servlet. On the contrary, the include action adds the response generated after executing the given page (a JSP/a servlet) and during the request processing phase when the user queries the page from his browser.
- The include directive statically inserts the resource content into the current JSP whereas the include action enables the current JSP page to attach a static/dynamic resource at run-time.
- Include directive works the best if the file rarely changes whereas the include action is best suited to the content that changes quite often.
Advanced level of JSP Interview Questions
31- What are the different scripting elements available in JSP?
JSP scripting elements let you embed the Java code into the servlet. Three forms of scripting elements are available in the JSP.
- Expression syntax is <%= Expression %>. They get evaluated and inserted into the output.
- Scriptlet syntax is <% Code %>. They get inserted into the servlet’s service method.
- A Declaration follows the syntax <%! Code %>. They get attached to the body of the servlet class, outside of any existing methods.
32- What is the right way to disable scripting?
You can disable the scripting by changing the <scripting-invalid> element of the descriptor for deployment to true. It is a child element of the <jsp-property-group> tag. You can only set it to a boolean value. Please check out the below sample to disable scripting.
// Sample to disable scripting <jsp-property-group> <url-pattern>*.jsp</url-pattern> <scripting-invalid>true</scripting-invalid> </jsp-property-group>
33- What is the right way to declare a method on a JSP page?
You can declare a method on a JSP page as a declaration.
Later you can call this method from any other methods of the JSP expressions or scriptlets.
For your note, there is no direct access allowed to the JSP implicit objects (request, response, session, etc.). But you can pass the JSP variables as parameters to the method that is declared.
34- Is it possible from a JSP page to process HTML form content?
Yes. You can fetch the data from the input elements of the form by using the request’s implicit object. It lies either as a scriptlet or an expression. Next, there is no need to implement any HTTP methods like <goGet()> or <doPost()> on the JSP page.
35- How to prevent direct access to JSP pages from the client browser?
We can utilize the WEB-INF location to place the JSP pages as a web application can’t access it directly from the customer’s browser. However, we need to configure it in the descriptor for deployment as we do for Servlets. Please refer to the below example to view the sample configuration.
// File: Web.xml // E.g. Sample config to prevent access to JSP pages <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>
36- Is JSP technology extensible?
YES. JSP technology is indeed extensible as it allows to creation of custom actions or tags for a large number of use cases. JSTL libraries enable this functionality in a JSP page.
37- Which of the JSP tags would you use to print the following text on a JSP page?
<br> Add a new line after every JSP interview questions
Use the <c: out> escapeXml attribute to escape the HTML to show it as text in the browser. Check out the below code to achieve this.
<c:out value="<br> Add a new line after every JSP interview questions" escapeXml="true"></c:out>
38- How to prevent page errors from printing on a JSP page?
Set up an “ErrorPage” attribute of the PAGE directory to the name of the error page in the JSP page template. After that use the following setting in the error page JSP.
// Set error page for JSP isErrorpage = "TRUE"
With the above attribute, you can stop the errors from getting displayed.
39- What is the best way to implement a thread-safe JSP page?
Apply the SingleThreadModel Interface on the JSP page.
You can get this done by adding the directive given in the below example.
// E.g. Enable thread-safety for a JSP page <%@page isThreadSafe="false" %>
40- How to restrict the caching of the JSP/servlet output on the client side?
Use the relevant HTTP header attributes to block the caching of JSP page output by the browser.
41- List out the major difference between a cookie and a JSP session.
Sessions are always preserved on the server side while the cookies have their way on the client end.
42- What is the correct way to delete cookies on a JSP page?
JSP gives you two ways to remove the cookies.
a) Set the age of the cookie to zero by calling the setMaxAge() method.
b) Set a timer in the header using the response. setHeader(expires { Specify the time } attribute). It will get the cookies removed after the defined time.
// Sample JSP code to set timer to remove cookies <% Cookie rmCookie = new Cookie("webCookie", null); rmCookie.setMaxAge(0); rmCookie.setPath("/"); response.addCookie(rmCookie); %>
43- How to forbid a JSP page from automatically creating a session?
The following code blocks the automatic creation of a session.
// Block automatic sessions <%@ page session="false">
44- How to embed the Java code in the HTML pages.
Please refer to the below code example which clearly answers the question.
// E.g. How to embed Java code in a HTML page < % @ page language = " java " %> <HTML> <HEAD><TITLE>JSP Interview Questions Page</TITLE></HEAD> <BODY> <% PrintWriter print = request . get Writer ( ) ; print . println ( " Welcome to the List of JSP Interview Questions!!!" ); %> </BODY> </HTML>
45- What is the way to pass data from one JSP to a JSP included in the page?
You can use the <Jsp: param> tag to pass the parameter from the main JSP to the included JSP page.
<jsp:include page="employee.jsp" flush="true"> <jsp:param name="empname" value="TechBeamers"/> <jsp:param name="empsalary" value="99999"/>
46- What do you mean by the output comment in the JSP context?
An output comment is part of the generated HTML of the JSP page. On the client side, you can see the comment from the page source in the Web browser.
JSP output comment syntax.
<!-- comment [ <%= expression %> ] --> e.g. <!-- Output comment is a part of the HTML shown to client. -->
The following text would appear in the page source in the web browser.
<!-- Output comment is a part of the HTML shown to client. -- January 24, 2004 –>
47- What do you mean by the Hidden Comment in the JSP context?
A hidden comment is one that doesn’t appear in the generated HTML of the JSP page. The JSP engine ignores it completely and discards any code lying inside the hidden comment.
It is useful in cases where you don’t want to show or “comment out” the sections in your JSP pages.
Using the closing –%> symbol in the hidden comment isn’t permissible. However, you can use it by escaping it after typing –%\>.
JSP Hidden comment syntax.
// Commenting syntax for JSP <%-- comment --%>
E.g.
<%@ page language="java" %> <html> <head><title>Check Hidden-Comment Example</title></head> <body> <%-- This text won't be visible in the HTML of this JSP page --%> </body> </html>
48- What is the need for using the HttpServlet Init method for memory-intensive operations that are executed once?
As you would know the loading of a servlet instance results in the invocation of the servlet init() method. It is by design the ideal location to run any expensive operations that require one-time execution.
The other reason is that the init() method is thread-safe and can safely cache all the instance variables of the servlet, which get read-only in the service method of the servlet.
49- Is it not advisable to create HttpSessions in a JSP, if yes then why?
JSP files generate the HttpSessions by default. This behavior is perfectly alright as per the J2EE design guidelines. But, if you don’t use the HttpSession in the JSP files then you can reduce the performance overhead by employing the JSP page directive as given below:
<%@ page session="false"%>
50- What would you do for printing the stack trace on a JSP page?
Stack trace helps to analyze a problem better while debugging the JSP code. It can guide a web developer to identify the method that produced the exception and isolate the source of that method.
However, there is no easy way to log the stack trace on a JSP page. You need to use the PrintWriter class to achieve this. Please follow the below code snippet that illustrates how to print a stack trace from a JSP error page:
<%@ page isErrorPage="true" %> <% out.println(" "); PrintWriter pWriter = response.getWriter(); exception.printStackTrace(pWriter); out.println(" "); %>
Must Read: 15 PHP Interview Questions and Answers for Experienced
Finally, let’s conclude this list of the best JSP interview questions and answers.
Wrapping Up…
Since JSP technology is critical from a web development perspective, the interviewer looks for candidates who have a decent level of knowledge of this subject. We’ve observed from our experience that you won’t strike in an interview just after reading the lengthy tutorials or having worked on live projects. There remain many areas that you may not have touched, and the interviewer could ask questions about that.
That’s why we built this ladder with the top 50 JSP interview questions. So that you can use it to take a step further in your career. If you want to praise our efforts, then please spread the word by sharing it on social media.
All the Best,
TechBeamers.