JSP Interview Questions
Table Of Contents
- What is JSP, and how does it differ from Servlets?
- What are the life-cycle methods of a JSP page? Explain each.
- What are JSP implicit objects? List them with their types.
- How do the jspand jsptags work in JSP?
- What is Expression Language (EL) in JSP, and how is it used?
- How many types of tags are provided by JSTL, and what are they?
- What are the primary differences between JSP custom tags and JavaBeans?
- What are the different scopes available for JSP actions, and when would you use each?
- What are the various implicit objects available in JSP Expression Language (EL)?
- What is the jspaction in JSP, and how can it be used to display applets?
If you’re preparing for an interview focused on JSP Interview Questions, you’ve come to the right place. These interviews often dive deep into your understanding of JavaServer Pages (JSP) and how you use them to build dynamic, interactive web applications. Interviewers typically ask questions about JSP lifecycle methods, scripting elements, and custom tags, along with scenario-based challenges like managing session data, handling exceptions, or embedding dynamic content in web pages. The goal is to test not only your technical expertise but also your ability to solve real-world problems using JSP.
In this guide, I’ve compiled a comprehensive set of JSP Interview Questions that will help you prepare confidently for your next interview. From basic concepts to advanced scenarios, each question comes with detailed answers and examples to solidify your understanding. Whether you’re a fresher brushing up on fundamentals or an experienced developer tackling complex use cases, this resource is tailored to make you interview-ready. Let’s get started on mastering JSP and securing your dream role!
Join our project-driven Java training in Hyderabad for complete guidance in mastering Java and excelling in your interviews. With hands-on sessions and expert-led interview preparation, we ensure you’re equipped to succeed in your Java career.
1. What is JSP, and how does it differ from Servlets?
In my experience, JavaServer Pages (JSP) is a technology that allows me to create dynamic web pages by embedding Java code directly into HTML. Unlike Servlets, which are entirely Java code and require extensive output generation methods like printWriter, JSP simplifies development by letting me mix Java and HTML seamlessly. JSP pages are eventually compiled into Servlets behind the scenes, but I find JSP more user-friendly when designing web pages with a lot of HTML.
For example, generating a simple “Hello, World!” page in Servlets looks like this:
public class HelloWorldServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body><h1>Hello, World!</h1></body></html>");
}
}With JSP, I can directly use HTML:
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>This makes JSP my go-to choice for web development when I want a cleaner and more readable approach.
See also:Â Lifecycle Methods in React JS Interview Questions
2. What are the life-cycle methods of a JSP page? Explain each.
When I work with JSP, I know it follows a lifecycle with three main methods: jspInit(), _jspService(), and jspDestroy().
jspInit(): This method is called once when the JSP page is initialized. I use it to perform setup tasks, like opening database connections._jspService(): This method is called for every request. It processes the request and sends back the response. I don’t usually write this method as it’s auto-generated by the JSP container.jspDestroy(): When the JSP page is unloaded from memory, this method is called. I use it to release resources, like closing database connections.
Here’s a practical example in Java:
<%!
public void jspInit() {
System.out.println("JSP is initialized. Setup complete.");
}
public void jspDestroy() {
System.out.println("JSP is being destroyed. Cleaning up resources.");
}
%>
<%= "Welcome to JSP Lifecycle Methods Example" %>This ensures proper initialization and cleanup, improving performance and reliability.
See also:Â Basic React JS Interview Questions for beginners
3. List some advantages of using JSP over other web technologies.
Based on my experience, JSP has several advantages:
- Ease of development: I can combine HTML and Java seamlessly, which simplifies creating dynamic web pages.
- Portability: Since JSP runs on Java, it works across all platforms with a compatible web server.
- Built-in objects: Objects like
request,response, andsessionare readily available, making my code cleaner and faster to write. - Tag libraries: JSP supports tag libraries like JSTL, which help me reduce the amount of Java code on the page.
- Automatic servlet generation: I don’t need to write the underlying Servlet code, as the JSP container handles it for me.
For example, using Java code with the JSTL library to display a list of items is straightforward:
<c:forEach var="item" items="${items}">
<p>${item}</p>
</c:forEach>This reduces complexity and makes the code easier to maintain compared to writing the same logic in Servlets.
4. How do you write comments in JSP? Explain the difference between JSP comments and HTML comments.
When I write comments in JSP, I can use two types: JSP comments and HTML comments.
- JSP comments: These are written as
<%-- comment --%>and are not visible in the client’s browser. I use them to document server-side logic. - HTML comments: These are written as
<!-- comment -->and are sent to the browser, so the user can view them by inspecting the page source.
Here’s an example using Java in JSP:
<%-- This is a JSP comment: it won't appear in the HTML output --%>
<!-- This is an HTML comment: it will be visible in the page source -->
<p>This content will be visible on the page.</p>Using the appropriate comment type ensures I keep sensitive information hidden while providing helpful hints for developers.
See also:Â Flipkart Angular JS interview Questions
5. What is the difference between the include directive and include action in JSP?
From my experience, the include directive (<%@ include %>) and include action (<jsp:include />) differ in how they include files.
- Include directive: This is processed at compile time. I use it for static content as the included file becomes part of the JSP page.
- Include action: This is processed at runtime. I use it when the content changes dynamically because it includes the latest version of the file.
Here’s an example of both:
<%@ include file="header.jsp" %>Include Action:
<jsp:include page="footer.jsp" />I use the directive for files that rarely change and the action for content that needs to be updated dynamically during runtime. This flexibility helps me optimize performance and usability in my applications.
See also:Â Basic React JS Interview Questions for beginners
6. What are JSP implicit objects? List them with their types.
In my experience, JSP implicit objects are predefined objects provided by JSP for my convenience. I don’t need to create them explicitly; they are available by default in every JSP page. They allow me to access and manage various aspects of a request, response, session, or application easily. Here are the most common implicit objects and their types:
request(HttpServletRequest): Helps me access client data, like form inputs or query parameters.response(HttpServletResponse): Allows me to modify the server’s response, like setting headers.session(HttpSession): Lets me store and retrieve user-specific data for a session.application(ServletContext): Useful for sharing data across the entire application.out(JspWriter): Helps me write output to the client.config(ServletConfig): Provides configuration details for the JSP page.exception(Throwable): Available only in error pages to handle exceptions.
Here’s a simple Java example that uses request and response:
<%
String username = request.getParameter("username");
if (username != null) {
out.println("Hello, " + username + "!");
} else {
response.sendRedirect("login.jsp");
}
%>In this example, I retrieve a query parameter using request and generate output with out. If the parameter is missing, I redirect the user using response.
See also:Â Design Patterns in Java
7. How do you make a JSP page thread-safe? What are the pros and cons of doing so?
In my experience, making a JSP page thread-safe involves synchronizing access to shared resources or using a thread-local scope. I achieve this by declaring the page as <%@ page isThreadSafe="false" %>, ensuring that the JSP container handles requests one at a time for this page.
Here’s an example in Java:
<%@ page isThreadSafe="false" %>
<%
synchronized (session) {
String count = (String) session.getAttribute("visitCount");
if (count == null) {
session.setAttribute("visitCount", "1");
} else {
int visitCount = Integer.parseInt(count) + 1;
session.setAttribute("visitCount", String.valueOf(visitCount));
}
}
%>In this code, I synchronize access to the session object to prevent multiple threads from modifying the visit count simultaneously.
Pros:
- Prevents race conditions, ensuring data consistency.
- Provides a safer environment when dealing with shared resources.
Cons:
- It reduces performance as only one thread processes the page at a time.
- It can lead to bottlenecks under heavy traffic.
See also:Â What are Switch Statements in Java?
8. How can you prevent the output of a JSP page from being cached by the browser?
I often prevent caching when I work with sensitive data or dynamic content. I achieve this by setting HTTP headers in the response object. This ensures that browsers don’t store a copy of the page locally.
Here’s an example in Java:
<%
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
response.setHeader("Pragma", "no-cache"); // HTTP 1.0
response.setDateHeader("Expires", 0); // Proxies
out.println("Caching disabled for this page.");
%>This snippet adds headers to disable caching completely. The Cache-Control directive prevents both caching and storage, while Pragma and Expires ensure compatibility with older browsers and proxies
9. What are the two ways to include the result of another page in JSP? Explain both.
In my experience, there are two ways to include another page’s content in JSP:
- Include Directive (
<%@ include %>): This includes a file at compile time. The included content becomes part of the JSP page, which is why I use it for static content. - Include Action (
<jsp:include />): This includes a file at runtime. It’s perfect for dynamic content because the included file is processed separately before inclusion.
Here’s an example in Java:
<%@ include file="header.jsp" %> <!-- Static inclusion -->
<jsp:include page="dynamicContent.jsp" /> <!-- Dynamic inclusion -->The directive is processed during the page compilation phase, while the action ensures the latest version of the included file is displayed at runtime.
See also:Â Scenario Based Java Interview Questions
10. How can you forward a request from a JSP page to a Servlet?
When I need to forward a request from a JSP page to a Servlet, I use the RequestDispatcher object. It lets me pass the control to another resource, like a Servlet, without involving the client.
Here’s an example in Java:
<%
String username = request.getParameter("username");
if (username == null || username.isEmpty()) {
RequestDispatcher dispatcher = request.getRequestDispatcher("ErrorServlet");
dispatcher.forward(request, response);
} else {
out.println("Welcome, " + username + "!");
}
%>Explanation:
- I use
request.getRequestDispatcher("ErrorServlet")to locate the target Servlet. - The
forward(request, response)method hands over the request and response objects to the Servlet without involving the client. - This keeps the URL unchanged while ensuring the Servlet handles business logic securely.
See also:Â Scenario Based Java Interview Questions
11. Can the exception implicit object be used in any JSP page? Why or why not?
No, the exception implicit object cannot be used in every JSP page. In my experience, it is available only in JSP pages configured as error pages. To enable this, I specify isErrorPage="true" in the JSP directive. This object holds details about the exception that triggered the error, helping me display meaningful error messages or debug issues.
Here’s how I define an error page and use the exception object:
<%@ page isErrorPage="true" %>
<%
String errorMessage = exception.getMessage();
out.println("Error occurred: " + errorMessage);
%><%@ page isErrorPage="true" %>: This directive indicates that the current JSP page is an error page, which allows access to theexceptionobject. Without this directive, theexceptionobject would not be available.exception.getMessage(): This retrieves the message associated with the thrown exception.out.println(): This outputs the error message to the response, providing feedback to the user or developer.
I use this approach when creating custom error pages to make debugging easier or to inform users about specific issues.
See also:Â Arrays in Java interview Questions and Answers
12. How is JSP used in the MVC model? What role does it play?
In my projects, JSP plays the View role in the Model-View-Controller (MVC) design pattern. It handles the presentation layer, rendering data received from the controller in a user-friendly format. JSPs work with Servlets (Controllers) that manage business logic and retrieve data from the Model (database or backend logic).
For example:
- Model: Retrieves data from a database (e.g., user info).
- Controller (Servlet): Processes requests and prepares data.
- View (JSP): Displays the data dynamically.
Here’s how a Servlet might forward data to a JSP:
// Servlet Code
request.setAttribute("username", "John Doe");
RequestDispatcher dispatcher = request.getRequestDispatcher("welcome.jsp");
dispatcher.forward(request, response);<!-- JSP Code -->
<%
String username = (String) request.getAttribute("username");
out.println("Welcome, " + username + "!");
%>This clear separation of responsibilities simplifies code maintenance and scalability.
See also:Â Accenture Java interview Questions and Answers
13. What are context initialization parameters in JSP? Where are they defined?
From my experience, context initialization parameters are application-wide settings defined in the web.xml file. These parameters store configuration data like database URLs, API keys, or global constants, making it easy to maintain and access such settings across the application.
Here’s an example of defining and accessing a context parameter:
web.xml:
<context-param>
<param-name>dbURL</param-name>
<param-value>jdbc:mysql://localhost:3306/mydb</param-value>
</context-param>JSP Code:
<%
String dbURL = application.getInitParameter("dbURL");
out.println("Database URL: " + dbURL);
%>Explanation:
The getInitParameter method retrieves the parameter value from the ServletContext. These parameters are useful for settings shared by the entire application.
14. What are the different scope values available for the jsptag?
The jsp:useBean tag supports the following scope values to define the lifespan of a bean:
page: The bean is available only on the current JSP page (default).request: The bean persists throughout the request lifecycle, shared across resources like Servlets or other JSPs.session: The bean exists for the user’s session.application: The bean is shared across the entire application, accessible by all Servlets and JSPs.
Here’s an example demonstrating request scope:
<jsp:useBean id="userBean" class="com.example.User" scope="request" />
<jsp:setProperty name="userBean" property="username" value="John Doe" />Explanation:
In this case, the userBean is available only for the current HTTP request and can be shared across components processing the same request.
See also: What are Switch Statements in Java?
15. What are JSP literals? Provide examples.
JSP literals represent fixed values used directly in code. They can be:
- String literals: Enclosed in double quotes (e.g.,
"Hello World"). - Numeric literals: Integers or floating-point numbers (e.g.,
42,3.14). - Boolean literals: Represent true or false (
true,false). - Null literal: Represents a null value (
null).
Example of using literals in JSP:
<%
String greeting = "Welcome to JSP!"; // String literal
int visits = 5; // Numeric literal
boolean isActive = true; // Boolean literal
out.println(greeting + " You've visited " + visits + " times.");
%>Explanation:
Literals simplify code by allowing me to directly define constant values within scripts or expressions. They are straightforward and essential for building dynamic content.
16. What is the purpose of the jsptag? How does it work?
In my experience, the jsp:useBean tag is a powerful way to work with JavaBeans in JSP. It simplifies data handling by creating or locating a JavaBean instance and associating it with a specific scope. It helps me encapsulate application logic in reusable components.
Here’s an example of how I use it:
<jsp:useBean id="userBean" class="com.example.User" scope="session" />
<jsp:setProperty name="userBean" property="username" value="Alice" />
<jsp:getProperty name="userBean" property="username" />Explanation:
- The
jsp:useBeantag looks for an existing bean in the specified scope (sessionin this case). If not found, it creates a new one. jsp:setPropertyassigns values to bean properties, whilejsp:getPropertyretrieves and displays them.
This approach allows me to separate business logic from presentation, enhancing maintainability.
See also: My Encounter with Java Exception Handling
17. How do the jspand jsptags work in JSP?
In my projects, I use jsp:setProperty and jsp:getProperty to interact with JavaBean properties directly in JSP pages. These tags provide a clean and readable way to set and retrieve property values.
Here’s an example:
<jsp:useBean id="userBean" class="com.example.User" scope="request" />
<jsp:setProperty name="userBean" property="username" value="Bob" />
<p>Welcome, <jsp:getProperty name="userBean" property="username" />!</p>Explanation:
jsp:setPropertyassigns the value"Bob"to theusernameproperty of the beanuserBean.jsp:getPropertyfetches the value of theusernameproperty and displays it on the page.
This method makes it easy to work with JavaBeans in a JSP-centric application.
18. What is the difference between ServletContext and PageContext in JSP?
From my experience, ServletContext and PageContext serve different purposes:
- ServletContext: Represents the entire web application and stores shared resources. It’s accessible to all JSPs and Servlets in the application.
- PageContext: Represents a single JSP page’s context, providing access to objects like request, response, and session within that page.
Here’s an example:
// Accessing ServletContext
String appName = application.getInitParameter("appName");
// Accessing PageContext
pageContext.setAttribute("greeting", "Hello, JSP!");
String greeting = (String) pageContext.getAttribute("greeting");
out.println(greeting);Explanation:
The application object accesses global settings, while pageContext is specific to the current page. I use ServletContext for global configurations and PageContext for page-level data sharing.
See also:Â Java and Cloud Integration
19. How does request.getRequestDispatcher() differ from context.getRequestDispatcher()?
In my projects, I use both request.getRequestDispatcher() and context.getRequestDispatcher() to forward requests, but they differ in scope:
request.getRequestDispatcher(): The path is relative to the current request, so I typically use it for forwarding within the same application module.context.getRequestDispatcher(): The path is relative to the application’s root, making it more suitable for forwarding to resources in other modules.
Example:
// Using request.getRequestDispatcher()
RequestDispatcher dispatcher = request.getRequestDispatcher("nextPage.jsp");
dispatcher.forward(request, response);
// Using context.getRequestDispatcher()
RequestDispatcher appDispatcher = getServletContext().getRequestDispatcher("/globalPage.jsp");
appDispatcher.forward(request, response);Explanation:
The first approach is useful for modular request handling, while the second is better for global navigation. I choose based on the relative or absolute nature of the resource path.
See also:Â What are Switch Statements in Java?
20. What is Expression Language (EL) in JSP, and how is it used?
In my experience, Expression Language (EL) in JSP simplifies data access and manipulation. Instead of using verbose Java code, EL lets me dynamically access and display data using simple expressions.
For example:
javaCopy code${userBean.username}
${userBean.username} This retrieves the username property of the userBean without writing a single line of Java code.
Here’s a practical example:
<jsp:useBean id="userBean" class="com.example.User" scope="session" />
<jsp:setProperty name="userBean" property="username" value="Charlie" />
<p>Welcome, ${userBean.username}!</p>Explanation:
EL enhances readability by removing scriptlets. It also supports implicit objects like requestScope, sessionScope, and functions for complex expressions, making JSP pages more declarative and easier to manage.
21. How can JSP technology be extended using custom actions or tags?
JSP technology can be extended using custom actions or custom tags, which allow developers to create reusable components that simplify page development. Custom tags are defined by creating a tag handler class that implements the Tag interface or extends the TagSupport class. This gives you the ability to encapsulate complex functionality into simple, reusable tags. For example, in my experience, I have created custom tags that handle tasks such as database interactions or formatting data dynamically within a page.
Below is an example where I create a simple custom tag that outputs a greeting message:
- Tag Handler Class:
public class GreetingTag extends TagSupport {
private String name;
public void setName(String name) {
this.name = name;
}
public int doStartTag() throws JspException {
try {
pageContext.getOut().write("Hello, " + name);
} catch (IOException e) {
throw new JspException("Error in GreetingTag", e);
}
return SKIP_BODY;
}
}- Tag Library Descriptor (TLD) file:
<tag>
<name>greeting</name>
<tag-class>com.example.GreetingTag</tag-class>
<attribute>
<name>name</name>
<required>true</required>
</attribute>
</tag>- Using the Custom Tag in a JSP:
<%@ taglib uri="http://example.com/tags" prefix="custom" %>
<custom:greeting name="John" />See also:Â Scenario Based Java Interview Questions
22. What is the purpose of the out implicit object in JSP?
The out implicit object in JSP is used to send output to the response stream, typically to display dynamic content on a webpage. It’s an instance of the JspWriter class, which is part of the JSP API. As a developer, I use it to directly write content like text, HTML, or even data dynamically generated by Java code. For instance, if I need to print a welcome message based on user input, I can use out.println() to send the result to the browser.
Here’s a simple example:
<%
String username = "Alice";
out.println("Welcome, " + username);
%>In this case, “Welcome, Alice” will be displayed on the browser. The out object is useful for directly sending dynamic content to the client.
23. How can we handle exceptions in JSP? Describe the available mechanisms.
Handling exceptions in JSP is crucial for providing a user-friendly experience and managing runtime errors. In my experience, the errorPage directive is one of the most useful mechanisms. This directive allows you to designate a specific JSP page as an error page, which will catch any unhandled exceptions from the current page. When an error occurs, the server redirects the request to this error page. I use this to show a customized error message to the user instead of exposing raw error details.
Additionally, JSP provides the exception implicit object, which contains the exception details. I can access this object in the error page to get more information about the error and display it to the user. For example, I might use the following in an error page to show a generic message:
<%@ page isErrorPage="true" %>
<%
Exception ex = (Exception) request.getAttribute("javax.servlet.error.exception");
out.println("An error occurred: " + ex.getMessage());
%>By setting isErrorPage="true", I inform the container that this page is responsible for error handling.
24. What is JSTL (JavaServer Pages Standard Tag Library), and how does it simplify JSP development?
JSTL (JavaServer Pages Standard Tag Library) is a collection of tags that provide common functionality for JSP pages, reducing the need for custom Java code. It simplifies JSP development by allowing developers to perform tasks such as iteration, conditional logic, formatting, and internationalization without writing Java code. For example, in my projects, I’ve used JSTL tags for looping over collections and displaying data without the need to write custom Java code for each operation.
JSTL also helps maintain separation of concerns in JSP by keeping business logic out of the page and allowing easier maintenance. The tag library includes various types of tags like core tags, SQL tags, XML tags, and internationalization tags. These built-in tags enable cleaner, more readable code, improving productivity and reducing errors. Using JSTL also makes it easier to support changes in the backend logic without altering the presentation layer.
See also: Â Arrays in Java interview Questions and Answers
25. How many types of tags are provided by JSTL, and what are they?
JSTL provides several types of tags to handle different common tasks in web development. The most widely used types include:
- Core Tags: These tags are used for basic flow control, like iteration (
<c:forEach>) and conditionals (<c:if>). They also support tasks like setting attributes (<c:set>) or including content (<c:import>). - Formatting Tags: These tags help format numbers, dates, and messages. For example,
<fmt:formatDate>can format a date according to a specific pattern. - SQL Tags: These tags help in performing SQL operations directly from the JSP, such as querying a database (
<sql:query>) or updating data (<sql:update>). - XML Tags: Used for XML-related tasks like parsing and transformation, e.g.,
<x:parse>and<x:transform>. - Internationalization Tags: These tags support localization and language-specific formatting, such as
<fmt:message>.
Each of these tag types makes my development process easier by abstracting away common functionality, so I don’t have to write repetitive Java code to perform common tasks.
26. What is the purpose of the jspand jspaction tags in JSP?
The jsp:forward and jsp:include action tags in JSP are used for including content from another resource within a JSP page, but they behave differently. The jsp:forward tag forwards the request and response to another resource, like a Servlet or another JSP page. Once the request is forwarded, the current JSP page stops execution, and the new page handles the request. I use jsp:forward when I need to redirect a request for processing elsewhere without changing the URL in the browser.
On the other hand, the jsp:include tag is used to include the output of another resource within the current JSP page. Unlike jsp:forward, the included resource’s content is inserted into the page at the point where the tag is used. This allows for dynamic inclusion of content, such as reusable header/footer templates. For instance:
<jsp:include page="header.jsp" />This would include the content of header.jsp in the current page’s response.
27. How can you disable session tracking in a JSP page?
Session tracking in JSP can be disabled by setting the session attribute to false in the page directive. By default, JSP pages automatically track sessions using cookies. However, when session tracking is not needed, or for specific pages where session management is handled elsewhere, I can disable it. Here’s how to do it:
<%@ page session="false" %>By setting the session attribute to "false", the page does not create a session for the user, and no session ID is passed to the browser. This is useful for static pages or pages that don’t require user-specific data or session management.
See also:Â Accenture Java interview Questions and Answers
28. What are the primary differences between JSP custom tags and JavaBeans?
JSP custom tags and JavaBeans serve different purposes in JSP development. Custom tags are essentially custom components created to encapsulate functionality, usually for repeated use across pages. They are defined by Java classes that implement tag handling logic and can be used directly within JSP files. I typically use custom tags to wrap repetitive tasks, like formatting or database interaction.
The main difference between custom tags and JavaBeans is in their purpose and functionality. Custom tags are used to encapsulate behavior or functionality, and they allow developers to define their logic in tag handlers. For example, here’s a simple custom tag that displays a message:
public class MessageTag extends TagSupport {
public int doStartTag() {
try {
pageContext.getOut().write("This is a custom message.");
} catch (IOException e) {
e.printStackTrace();
}
return SKIP_BODY;
}
}JavaBeans, on the other hand, are simple Java classes used to store and manage data. They follow specific conventions (like having private fields and public getters/setters). For example:
public class UserBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}29. How do you create and use custom tags in JSP? Explain the steps involved.
To create and use custom tags in JSP, I follow these steps:
- Create a Tag Handler Class: I first define a Java class that implements the
Taginterface or extendsTagSupport. This class contains methods to handle the tag’s lifecycle, such asdoStartTag()anddoEndTag(). - Define the Tag in the TLD File: I then create a Tag Library Descriptor (TLD) file where I declare the tag, its attributes, and its handler class. This XML file tells the JSP container how to map the tag in the JSP to its corresponding handler class.
- Use the Custom Tag in JSP: Finally, I use the custom tag in the JSP file by importing the tag library and calling the custom tag using the tag name.
Here’s an example:
// TagHandler.java
public class MyTagHandler extends TagSupport {
public int doStartTag() {
try {
pageContext.getOut().write("Hello from custom tag!");
} catch (IOException e) {
e.printStackTrace();
}
return SKIP_BODY;
}
}The tag handler performs the business logic, and I can use this tag in a JSP page after defining it in the TLD file.
See also: What are Switch Statements in Java?
30. How can applets be embedded and displayed within a JSP page?
Applets can be embedded in a JSP page using the <applet> tag, similar to how they are embedded in regular HTML. However, this technique has become outdated as applets are deprecated in modern browsers due to security concerns. That said, for older applications that still require applets, I can embed them within a JSP page as follows
<applet code="HelloWorldApplet.class" width="300" height="300">
Your browser does not support applets.
</applet>The code attribute specifies the applet class, while width and height set the dimensions of the applet display area. In my current projects, I avoid using applets and prefer using more modern technologies like JavaScript or HTML5 for client-side interactivity.
31. What is the difference between ServletContext and PageContext objects in JSP?
In my experience, both ServletContext and PageContext are important objects in JSP, but they serve different purposes. The ServletContext object is used to store information about the entire web application, like global configurations or application-wide parameters. It’s shared across all JSP pages and Servlets in the application, and I use it to access resources like database connections that are relevant to the whole application. For example, I can get an initialization parameter from ServletContext like this:
// Retrieve ServletContext from the current page
ServletContext context = getServletContext();
// Retrieve an initialization parameter from web.xml
String dbURL = context.getInitParameter("dbURL");
// Use the parameter value to establish a connection
Connection conn = DriverManager.getConnection(dbURL, "username", "password");On the other hand, PageContext is specific to a single JSP page and provides access to page-specific attributes, such as request, response, session, and application attributes. It helps manage the page’s lifecycle and provides access to the request and response objects. I use PageContext to interact with the page-specific implicit objects and other resources during the JSP page execution.
See also:Â Design Patterns in Java
32. How is caching disabled when navigating back in the browser after a JSP response?
To disable caching in a JSP response, I would use HTTP headers to tell the browser not to cache the page. This can be achieved by setting the Cache-Control, Pragma, and Expires headers in the response object. These headers make sure that the browser fetches the page anew when navigating back, preventing it from using a cached version. Here’s how I would set these headers:
// Set Cache-Control header to prevent caching
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
// Set Pragma header for older HTTP 1.0 browsers
response.setHeader("Pragma", "no-cache");
// Set Expires header to a past date to indicate that the page is expired
response.setHeader("Expires", "0");The Cache-Control header ensures that the page is not cached by proxies, while the Expires header tells the browser that the page has expired. By setting these headers, I can ensure that a fresh request is made each time the user navigates back to the page.
33. What are the different scopes available for JSP actions, and when would you use each?
In JSP, there are four primary scopes:
- Page Scope: Variables are available only within the page where they are defined. I use page scope when I need data to be visible only within a single JSP page. It’s ideal for temporary data that won’t be used elsewhere.
// Example of setting an attribute in page scope
pageContext.setAttribute("username", "Alice");
// Accessing the attribute later in the page
String username = (String) pageContext.getAttribute("username");- Request Scope: Variables exist for the duration of a single HTTP request and can be shared across multiple JSP pages during the same request. I typically use request scope to pass data between pages during the same request, like a search query or form data.
// Setting a request attribute
request.setAttribute("searchQuery", "Java");
// Retrieving request attribute in a different page
String query = (String) request.getAttribute("searchQuery");- Session Scope: Variables are stored for the duration of the user’s session and can be accessed across multiple pages. I use session scope to store user-specific data, such as login information or shopping cart details.
// Storing user info in session
session.setAttribute("user", "JohnDoe");
// Retrieving user info from session on another page
String user = (String) session.getAttribute("user");- Application Scope: Variables are available across the entire application, shared by all users. I use application scope when I need data to be accessible globally, like an application-wide setting.
// Setting an attribute in the application scope
servletContext.setAttribute("appVersion", "1.2.3");
// Accessing the attribute globally
String version = (String) servletContext.getAttribute("appVersion");Each scope serves different needs, and I choose which one to use based on the lifespan and visibility of the data.
34. Can you implement an interface in a JSP file? Explain why or why not.
No, JSP files cannot directly implement interfaces because JSP is meant to be a declarative page that generates dynamic content, not for implementing Java code. While JSP can contain expressions and scriptlets, it does not support implementing interfaces directly. However, I can use Java classes, such as JavaBeans or Servlets, which implement interfaces, and then access those beans or classes in the JSP. For example, if I have a User interface and an UserImpl class, I would use a JavaBean in the JSP like this:
<jsp:useBean id="user" class="com.example.UserImpl" scope="session" />
// Accessing the bean property in the JSP
<p>Welcome, ${user.username}</p>The JSP interacts with the JavaBean, which can implement any necessary interfaces, but the JSP itself does not directly implement interfaces.
35. What are the various implicit objects available in JSP Expression Language (EL)?
In JSP Expression Language (EL), several implicit objects are automatically available for use, and these make it easier for me to interact with dynamic data in the page. The most commonly used implicit objects include:
- pageContext: Provides access to page-related attributes, like request and response objects.
// Accessing pageContext in EL
${pageContext.request}- requestScope: Allows access to request-level attributes that are set during the request lifecycle.
// Accessing a request-scoped attribute
${requestScope.user}- sessionScope: Provides access to session-level attributes, which persist across multiple requests from the same user.
// Accessing a session-scoped attribute
${sessionScope.username}- applicationScope: Provides access to attributes that are available globally throughout the entire web application.
// Accessing an application-scoped attribute
${applicationScope.appVersion}- param: Retrieves query parameters from the URL. For example,
${param.username}fetches theusernameparameter from the query string.
// Accessing a request parameter
${param.username}- cookie: Allows access to cookies sent from the client to the server.
// Accessing a cookie
${cookie['username'].value}- header: Provides access to HTTP request headers.
// Accessing a header value
${header['User-Agent']}- initParam: Retrieves initialization parameters defined in the web application’s
web.xml.
// Accessing an init parameter
${initParam.dbURL}For example, to access the username parameter from a URL in EL, I would use ${param.username}. This makes EL a powerful tool for working with request, session, and application data in a more intuitive way.
36. What is the purpose of jspand jspin JSP, and how do they work?
The jsp:setProperty and jsp:getProperty actions are used for interacting with JavaBeans in JSP. They provide a simple way to set and get properties of JavaBeans without needing explicit Java code.
- jsp: Sets the value of a property in a JavaBean. I use this action when I need to assign a value to a bean’s property directly within the JSP.
<jsp:useBean id="userBean" class="com.example.User" />
<jsp:setProperty name="userBean" property="username" value="Alice" />This action sets the username property of the userBean to "Alice".
2. jsp: Retrieves the value of a property from a JavaBean. I use this action to display the value of a property on the JSP page.
<jsp:getProperty name="userBean" property="username" />This action retrieves the value of the username property of the userBean and displays it on the page. These actions make it easier to manipulate JavaBeans within JSP pages by reducing the amount of Java code I need to write. They enable data binding between the JSP page and the JavaBean, streamlining the process of displaying and modifying data.
37. How do you include the output of one JSP page in another? Discuss the options.
There are two primary ways to include the output of one JSP page in another: static inclusion and dynamic inclusion.
- Static Inclusion: This method includes the content of another page at compile-time. I use the
includedirective for this.
<%@ include file="header.jsp" %>The content of header.jsp is included directly into the current JSP page at the time the page is compiled.
2. Dynamic Inclusion: This method includes the content of another page at runtime. I use the jsp:include action for dynamic inclusion.
<jsp:include page="footer.jsp" />This action allows me to include dynamic content from another JSP page during the request lifecycle. I use dynamic inclusion when the included content is dependent on runtime conditions, such as user input or session data. Unlike static inclusion, which is faster but more limited, dynamic inclusion provides greater flexibility. I prefer using dynamic inclusion when I need to load content like menus, headers, or footers that might change based on the user session or request parameters.
38. What is the function of the session object in JSP, and how is it used for session tracking?
The session object in JSP is used to track user-specific data across multiple requests from the same client. When a user accesses a JSP page, a session is created for them, and I can store session-specific data, such as login credentials or shopping cart items, in the session. The session object helps identify users across multiple requests. Here’s how I use it to store and retrieve session data:
// Storing data in the session
session.setAttribute("username", "Alice");
// Retrieving data from the session
String username = (String) session.getAttribute("username");The session object automatically generates a session ID and sends it as a cookie to the client, which allows the server to associate multiple requests from the same user. This makes session tracking essential for handling user-specific data like authentication and user preferences.
39. What is the jspaction in JSP, and how can it be used to display applets?
The jsp:useBean action is used to instantiate a JavaBean within a JSP page. It simplifies the process of creating and accessing JavaBeans without having to write Java code manually. I use jsp:useBean to initialize a JavaBean and set its properties. While JSP doesn’t directly handle applets, I can still use this action to interact with JavaBeans that could, in turn, manage applet logic or properties.
<jsp:useBean id="myBean" class="com.example.MyBean" scope="session" />If I wanted to use an applet alongside a JavaBean in a JSP, I could initialize the applet using <applet> tags and the jsp:useBean to set properties for the applet. However, applet support has been deprecated in most modern browsers, and applets are rarely used in contemporary web development.
40. Explain the difference between static inclusion using the include directive and dynamic inclusion using the jspaction.
Static inclusion using the include directive happens at compile-time. This means the contents of the included file are inserted directly into the current JSP during the compilation phase. This is faster because the inclusion occurs only once during page compilation, and the included content is fixed. Here’s how I’d use static inclusion:
<%@ include file="header.jsp" %>In contrast, dynamic inclusion using the jsp:include action happens at runtime, meaning the content is included every time the page is requested. It is more flexible because the included content can change based on runtime conditions, such as user input or session data. Here’s how I’d use dynamic inclusion:
<jsp:include page="footer.jsp" />Dynamic inclusion is better for including content that might change or need to be reloaded each time a page is accessed, while static inclusion is more efficient for fixed content.
Conclusion
Mastering JSP (JavaServer Pages) is essential for any web developer looking to create dynamic, interactive, and efficient Java-based web applications. By understanding key concepts such as implicit objects, JavaBeans, session management, and content inclusion, developers can build sophisticated solutions that meet real-world demands. JSP provides the flexibility to design responsive and scalable applications, making it a powerful tool in a developer’s toolkit. Whether you’re handling user inputs, managing sessions, or dynamically generating content, JSP offers the features and functionality you need to build cutting-edge web applications.
For anyone preparing for a JSP interview, having a solid understanding of these concepts will set you apart from the competition. Mastering these technical aspects not only equips you to answer interview questions confidently but also enables you to contribute effectively to complex projects. In today’s fast-evolving tech landscape, JSP remains a cornerstone for building dynamic websites and applications, and understanding it thoroughly opens doors to exciting opportunities in the world of web development.

