| Aspect | JSP | Servlet | 
| Role | Primarily used for view (presentation layer) with HTML and tag libraries | Java classes used for business logic or controller | 
| Ease of use | Uses HTML‑like syntax with built‑in tags and implicit objects; easier to maintain by designers | Pure Java code; requires writing HTML in Java code | 
| Translation | A JSP page is translated into a servlet during the first request, causing a slight delay | Already compiled Java class; no translation overhead | 
| Implicit objects | Provides implicit objects such as request, response, out, session, etc., enabling easier access to request/response data | Does not provide implicit objects; developers must create them | 
| Session management | Automatic session creation; the session implicit object is available. | Session handling must be written manually | 
4. What is the life cycle of a JSP page?
A JSP page has a number of phases that it goes through in the container:
- Translation – The container checks to see if the resulting servlet is older than the JSP. If it is, then it translates the JSP into a servlet source file. 
- Compilation – The servlet source is compiled into a class. 
- Loading and instantiation – The servlet class is loaded into memory, and an instance of the object is created. 
- Initialization – The jspInit() method is called. Developers can override this method to perform one-time initialization. 
- Request processing – For each request, the _jspService() method is called. This method handles HTTP methods and writes to the response. 
- Destruction – Once the JSP is unloaded from the webapp, jspDestroy() is called to release resources.
5. Which JSP lifecycle methods can be overridden?
A developer can override two methods: jspInit() and jspDestroy(). These correspond with the initialization and destruction phase of the life cycle.  The _jspService() method is generated by the container and should not be overridden.
6. What are the types of elements in JSP?
JSP contains many different types of elements.
- Directives – Provide global-level instructions (page, include, taglib, etc.).
- Scripting elements – Place Java code within (scriptlet, expression, declaration).
- Actions – XML-like tags that execute tasks within JSP code (includes, beans, forwards, etc) (jsp:useBean, jsp:setProperty, jsp:include).
- Comments – Note for the developer; not sent to client. (<%– comment –%>)
- Expression language (EL) – Simplified syntax to access data utilizing ${…}
- Tag libraries – Collection of custom tags (JSTL).
7. What are JSP directives?
JSP directives provide instructions to the JSP engine about how to address the page as a whole. They are defined with <%@ … %>. Any directives that are defined do not have output. JSP directives determine properties like imports, session, error page, tag libraries, etc.
8. What are the types of JSP directives?
There are three specific types of directives:
- page directive: Defines page-wide attributes, like import, session, buffer, autoFlush, contentType, errorPage, isErrorPage, extends, isELIgnored, etc.
- include directive: Includes another file statically computed at translation time. If the included file changes, the file must be recompiled to take effect.
- taglib directive: Declares a tag library to allow the use of custom tags or JSTL tags.
9. What is a page directive, and what are its attributes?
A page directive specifies page-level properties. Some of the important attributes available are:
- import: to import Java classes or packages.
- Session: to indicate whether an HttpSession will be created (default is true). Setting session = “false” prevents the automatic session creation.
- buffer: size of the response buffer.  An 8k or “none” value indicates there is no response buffer.  When buffer=”none”, any output will be sent to the client directly.
- autoFlush: If set as true (or default), the buffer will be automatically flushed if full, and if set to false, a buffer overflow would cause an exception to be thrown.
- contentType: is used to specify the mime type and character encoding (ex. text/html; charset=UTF-8)
- errorPage/isErrorPage: errorPage specifies a URL to a JSP that will handle unhandled exceptions. In this JSP, you will need to set isErrorPage=”true” to access an implicit object, exception.
- extends: allows the servlet generated to extend a custom superclass.
- isELIgnored: If set to true, any Expression Language expressions will not be evaluated, but if false, they will.
10. What is the difference between include directive and include action?
Both are used to include content from another resource, but they behave differently:
| Feature | Include Directive (<%@ include file=”…” %>) | Include Action (<jsp:include page=”…” />) | 
| When inclusion occurs | Translation time – the content of the included file is merged into the main JSP during translation | Request time – the included resource is processed for every request, and the output is inserted into the response | 
| Effect of changes | Changes to the included file require recompiling the main JSP | Changes take effect immediately on the next request | 
| Parameter passing | Cannot pass parameters | Can pass parameters via <jsp:param> child tags | 
| Use case | Static templates (e.g., header/footer) | Dynamic content that may change independently | 
 
11. What is a JSP scriptlet?
A scriptlet is a block of Java code embedded in a JSP using <% … %>. The code gets inserted into the _jspService() method and is executed on every request. To write output, the out object (a JspWriter) must be used to write to the response. Scriptlets are not recommended in modern JSP because they mix Java and HTML; alternatively, use JSTL or EL.
12. What is a JSP declaration?
A declaration is used to declare class‑level instance variables or methods in a JSP. It is defined using <%! … %>. Declarations are inserted outside of the _jspService() method, which is what causes the variables and methods to be part of the autogenerated servlet class.
<%! private int counter = 0; %>
<%! public int factorial(int n) { return (n <= 1) ? 1 : n * factorial(n - 1); } %>
This code declares a field counter and a method factorial() available to the JSP.
13. What is a JSP expression?
An expression is used to output the results of a Java expression directly into the response. It uses the syntax <%= expression %>. When the JSP executes, the expression is evaluated and converted into a string, then added to the output. Unlike scriptlets, an expression implicitly calls out.print() and is simpler to write when displaying values.
14. What is the JSP Expression Language (EL)?
The Expression Language (EL) is a way to access variables as well as perform simple operations in JSP pages with a shorter notation than Java code. Expressions are noted as ${…}. EL allows arithmetic or logical operations and retrieves application data like request parameters, headers, and scoped attributes with less overhead. It offers these capabilities without Java code embedded, and there is automatic type conversion and null handling where appropriate. EL also has a set of its own implicit objects available (such as requestScope, sessionScope, param, header, cookie).
15. What are JSP comments and their types?
There are two forms of comments there are two styles of comments:
- JSP comments use <%– comment –%>, which is stripped out by the JSP engine; these comments are not sent to the client and are invisible to the client’s browser.
- An HTML comment uses and these comments are sent to the client and would be visible when viewing the source.
16. What are JSP implicit objects?
JSP has a number of implicit objects that developers can use immediately without declaration:
- request – Represents the HttpServletRequest object that holds the client request data.
- response – Represents the HttpServletResponse object that allows the developer to set response headers, cookies, etc.
- out – A JspWriter object that can send content to the client.
- session – The HttpSession object related to the client.
- application – The ServletContext object for the app.
- config – The ServletConfig object that holds the initialization parameters.
- pageContext – Provides access to various scoped attributes.
- page – A reference to the particular servlet that is generated.
- exception – It is available only on error pages, and holds the exception that caused the forwarding.
All of these objects simplify access to common resources and help provide the differentiation between JSP and pure servlets.
17. What is the use of the session implicit object?
The session object represents the current HttpSession, allowing the storing and retrieval of user‑specific data between multiple requests (only one session per user). The JSP container automatically creates a session for each client unless the developer disables sessions using the session=”false” in the page directive. Developers have methods to manage data in the session (session.setAttribute() or session.getAttribute()), and they can end the session using session.invalidate().
18. What is the difference between JSP and JavaScript?
JavaScript is a client‑side scripting language executed in browsers, whereas JSP is a server‑side technology executed on the server. A few key differences:
| Aspect | JSP | JavaScript | 
| Execution environment | Runs on the server (servlet container); generates HTML/JavaScript | Runs on the client (browser) or server (Node.js) | 
| Language | Java-based; part of Java EE | ECMAScript standard | 
| Primary use | Create dynamic pages and interact with server resources | Enhance client‑side behaviour, form validation and dynamic UI | 
| Complexity | More complex; integrates with Java code and tag libraries | Lightweight; dynamic typing and simpler syntax | 
| File extension | .jsp compiled to a servlet | .js directly interpreted | 
| Support for HTML | JSP templates embed HTML and allow Java code within them | JavaScript code runs within HTML pages, but cannot embed HTML code into the script itself. | 
 
19. What is the buffer attribute in JSP, and what happens if it is set to none?
The buffer attribute of the page directive sets the size of the response buffer (e.g., 8 KB). If you set it to none, that disables buffering and sends output straight to the client, therefore you cannot use flush and cannot redirect the response or invoke error pages after the content has been sent.
20. What does the autoFlush attribute do in JSP?
autoFlush controls how the buffer behaves when it reaches a threshold. When autoFlush=”true” (the default), once the buffer is full, it automatically flushes the content to the client. If set to false, then the container will throw an exception once the buffer becomes full, allowing developers to determine what to do about it, instead of just putting up with an automatic flush.
21. What is the contentType attribute in JSP?
contentType allows you to set the MIME type and optionally character encoding of the response. For example: <%@ page contentType=”text/html;charset=UTF‑8″ %> tells the JSP container to interpret the response as HTML encoded with UTF‑8 character code. This is really important when working with character encoding, as you want to set it correctly before deploying your application.
22. What is the errorPage attribute, and how is it used?
The errorPage attribute names a JSP page that handles uncaught exceptions. If an uncaught exception occurs in the main JSP, the container forwards control to the specified error page. The error page must declare isErrorPage=”true” to be able to access the implicit exception object to display error information.
23. What are JSP literals and operators?
JSP uses Java literals and operators because it is built on Java. Literals include strings (“Hello”), numbers (42), booleans (true/false), characters (‘A’), and null. Operators include arithmetic (+, -, *, /), comparisons (==, <, >), logic (&&, ||), assignment (=), and string concatenation. When using Expression Language there are different operators, such as empty and == relating to null.
24. What is the session attribute in the page directive?
session controls whether the JSP participates in HTTP session management. The default setting for the session is true, enabling the JSP to create or use an existing HttpSession and expose the session implicit object. If the session is set to false, the JSP will not create a session, and the session implicit object will not be available.
25. What is the include directive used for?
The include directive (<%@ include file=”header.jsp” %>), is good for including the content of another file into the current JSP document at translation time. It is normally used for including static pieces like headers or footers. Because it is included at translation time, the JSP will need to be recompiled after changes have been made to the included file.    
26. What is the purpose of the extends attribute in page directive?
The extends attribute allows the generated servlet to extend another class. This will allow the JSP to inherit common methods or fields from the parent class. To specify a superclass, the syntax would be <%@ page extends=”com.example.BaseServlet” %>.
27. How does JSP handle character encoding?
Character encoding is supported by the contentType attribute and response header. By setting contentType=”text/html;charset=UTF-8″, they are setting the character encoding for the response. This means the writer will also use the specified encoding. In addition, <%@ page pageEncoding=”UTF-8″ %> will specify the JSP file to be parsed using UTF-8. If the content is not encoded correctly, internationalized characters will likely be misinterpreted. 
28. How does JSP work internally?
Internally, the first time a JSP is requested, the container examines whether the servlet source is current. If it is not current, then the JSP is transformed into a Java source file corresponding to a servlet; the servlet is then compiled to produce an executable class, and the class is loaded into memory. The execution of the servlet and all requests that it handles occurs via the _jspService() method of the servlet; the servlet processes and then returns generated HTML code to the web browser. Subsequent requests to the same JSP will reuse the compiled version of the servlet, unless the JSP has changed.
Intermediate JSP Interview Questions
This section will consist of Intermediate JSP Interview Questions and Answers that describe realistic user-facing features of applications like JSTL, EL, session handling, custom tags, and JSP actions. These Intermediate JSP Interview Questions and Answers are intended for developers who are being prepared for interviews that assess their practical knowledge of JSP and ability to build dynamic Java-based applications for web applications.
29. What are JSP action tags?
Action tags are XML-style tags prefixed with the string jsp:. Action tags perform some action at request time, such as or forwarding a request to, a resource, using JavaBeans, creating an instance of an object, or generating the use of a plug-in. Some of the action tags include: jsp:useBean, jsp:setProperty, jsp:getProperty, jsp:include, jsp:forward, jsp:param, and jsp:plugin.
30. What is the jsp:useBean action and how is it used?
<jsp:useBean> is used to create or locate a JavaBean. They typically consist of attributes: id, class (full class name of the bean), and scope (options are page, request, session and application). If the bean does not already exist in the requested scope, the container will create it; if it exists in scope, the container will return the existing bean instance. Example:
<jsp:useBean id="user" class="com.example.UserBean" scope="session" />
31. What is the jsp:setProperty action?
<jsp:setProperty> sets a property on a bean from a request parameter or a literal value. It must appear within or after a jsp:useBean. Common attributes include: name (io of the bean), property (name of the property or * for all matching request parameters), and optional value. Example:
<jsp:useBean id="user" class="com.example.UserBean" />
<jsp:setProperty name="user" property="userName" param="username" />
32. What is the jsp:getProperty action?
<jsp:getProperty> outputs the value of a property of the bean to the response. Attributes: name (bean id) and property. 
Example: 
<jsp:getProperty name="user" property="userName" /> prints the userName property of the bean.
33. What is the jsp:forward action, and how does it differ from sendRedirect()?
<jsp:forward page=”/other.jsp” /> forwards the request and response objects to some other resource (JSP, servlet, or HTML) on the same server. Forwarding happens on the server-side so request parameters are preserved and the URL does not change in the browser. Conversely, response.sendRedirect() sends an HTTP redirect to the client which causes the browser to request a new URL. Additionally, a redirect will change the URL in the address bar. Redirects are typically used when moving from the JSP to an external site, or when implementing a POST-redirect-GET pattern.
34. What is the jsp:include action and when should you use it?
<jsp:include page=”fragment.jsp” flush=”true” /> action includes another resource at request time and includes that resource’s output into the call JSP. This action allows dynamic inclusion of servlets or JSPs that could change over time. You should use this action when including content that is dynamic or could change regularly. Unlike the include directive, when changes are made to the included content, the parent JSP does not have to recompile.
35. What is a JavaBean in JSP, and how do you access it?
A JavaBean is a reusable Java class that follows a specific set of naming conventions (public no-arg constructor and private fields with getters/setters). JavaBeans are typically used in JSPs to encapsulate business or form data. You typically access JavaBeans in JSPs using jsp:useBean, jsp:setProperty, and jsp:getProperty actions. JavaBeans can also be stored in the page, request, session, or application scopes to be used later and are accessible with EL via ${bean.property}.
36. How can we avoid direct access to JSP pages from a client browser?
To prevent request access to the JSP pages:
- Place JSPs under the WEB-INF directory so they cannot be accessed directly by a URL.
- Use the Front Controller pattern to route all requests through a servlet that performs logic and forwards to JSP pages.
- Security constraints can be configured for the web.xml or use a framework (such as Spring MVC), which will set up the JSPs behind controllers.
37. How can we prevent automatic session creation in JSP?
JSP automatically creates a new session object per client. This can be turned off for a given JSP page by adding the session=”false” page directive to the JSP page. The session’s implicit object will not be available, and if referenced, an error will occur.
38. What is the difference between JspWriter and PrintWriter?
JspWriter is the class of the out implicit object that extends java.io.Writer and performs buffering of output to the client. The Tomcat API says JspWriter emulates both BufferedWriter and PrintWriter, but throws IOExceptions from the print methods instead of swallowing them. PrintWriter (used in servlets) does not throw IOException. JspWriter may or may not use an underlying PrintWriter, depending on whether it performs buffering. In general, prefer JspWriter in JSP files and PrintWriter in servlets.
39. How can we read and write cookies in JSP?
To write a cookie, create a Cookie object with the name and value you want, set any optional attributes such as maximum age, and add it to the response:
Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
firstName.setMaxAge(60 * 60 * 24);  // Store for 24 hours
response.addCookie(firstName);
To read cookies, use request.getCookies() to retrieve an array, loop over the retrieved array of cookies, and find the name/value you are interested in. You can use cookies in this way to track a session or store user preferences.
Cookie[] cookies = request.getCookies();
if (cookies != null) {
    for (Cookie cookie : cookies) {
        if (cookie.getName().equals("first_name")) {
            String firstName = cookie.getValue();
            // Use the value as needed
        }
    }
}
40. How do you delete cookies in JSP?
To delete a cookie, read it as previously mentioned, set its maximum age to zero via cookie.setMaxAge(0), and add it back to the response. This tells the browser to remove the cookie.
41. How is session management handled in JSP?
JSP sessions are managed using the HttpSession implicit object. A session is automatically created when a client accesses a JSP. Developers can store attributes with session.setAttribute() and retrieve them with session.getAttribute(). The session persists across multiple requests until it expires or is invalidated. Session tracking can be achieved via cookies, URL rewriting (response.encodeURL()), hidden form fields, or the jsessionid parameter. Automatic session creation can be disabled using session=”false”.
42. How can you delete session data?
You can remove individual attributes using session.removeAttribute(name). To invalidate the entire session, call session.invalidate(). You can also set a session timeout by calling session.setMaxInactiveInterval(seconds) or specify it globally in web.xml using <session-config><session-timeout>…</session-timeout></session-config>.
43. How do you read form data using JSP?
When the form is submitted with method=”GET” or method=”POST”, the form data is made available as request parameters. You can use request.getParameter(name) for a single value, request.getParameterValues(name) for multiple values for the same name (for example, checkboxes), or request.getParameterNames() for iterating all parameter names. For file uploads or binary data, use request.getInputStream() and the data will be encoded as multipart/form-data.
44. What is JSTL?
The JavaServer Pages Standard Tag Library (JSTL) is a set of standard tags provided with Java EE to perform common tasks, such as iteration, conditionals, URL handling, formatting, and database access. It replaces the need for scriptlets and promotes a cleaner separation of logic from presentation.
45. What are the types of JSTL tags?
JSTL is divided into tag libraries:
- Core tags (c prefix) – Iteration, conditionals, variable support, URL handling, and redirection.
- Formatting and internationalisation tags (fmt prefix) – Formatting of numbers, dates, and messages.
- SQL tags – (sql prefix) – Data access class to interact with databases (for prototyping only).
- XML tags (x prefix) – Processing XML documents.
- Functions (fn prefix) – String related functions, such as length, substring, and contains.
46. What are the core tags in JSTL and their uses?
Core tags include:
- <c:out> – Outputs a value escaping HTML.
- <c:set> – Sets variable values in a specified scope. Attributes include var, value, scope, target, and property.
- <c:remove> – Removes a scoped variable.
- <c:catch> – Catches exceptions within its body.
- <c:if> – Conditional execution.
- <c:choose> with <c:when> and <c:otherwise> – Multi‑branch conditional.
- <c:forEach> – Iterates over collections.
- <c:forTokens> – Iterates over tokens in a string.
- <c:param> – Adds parameters to URLs or redirects.
- <c:redirect> – Performs a redirect within the application.
- <c:url> – Creates URL with optional query parameters.
47. What is the <c:set> tag used for?
<c:set> is used to assign a value to a variable or JavaBean property. The attributes var (the name of the variable), and value (the value you want to assign to the variable) are the most used. You can also assign variable values as scoped attributes using the optional scope attribute, which specifies whether you want to specify the page, request, session, or application scope. You can also use it to assign properties of your JavaBeans using the optional target and property attributes. 
48. What is the <c:remove> tag used for?
<c:remove> removes a variable from a specified scope. You specify the name of the variable using the var attribute, whether you want to remove the variable from the page, request, session, or application scope can be handled using the optional scope attribute. If you do not specify a scope, it will remove the variable from all scopes.
49. What is the <c:choose> tag used for?
<c:choose> provides conditional logic similar to a switch statement. It contains one or more <c:when> tags followed by an optional <c:otherwise>. The first <c:when> whose test evaluates to true is executed; otherwise, <c:otherwise> runs. It helps avoid nested if statements and improves readability.
50. What is the <c:redirect> tag used for?
<c:redirect> redirects the request to another URL within the application. It accepts a url attribute and can be combined with <c:param> to pass query parameters. It performs a client‑side redirect similar to response.sendRedirect() but within JSTL.
51. What is the <c:url> tag used for?
<c:url> constructs a URL with proper URL encoding. Attributes include value (the URL path), an optional var to store the result, and a scope to specify where to store it. Nested <c:param> tags can append query parameters.
52. What are JSTL SQL tags?
JSTL SQL tags allow prototype database operations using simple tags (not recommended for production). Key tags:
- <sql:setDataSource> – Defines a data source for database connections. Attributes include var, driver, url, user, password, and scope.
- <sql:query> – Executes SELECT queries. Attributes: dataSource, sql, startRow, maxRows, and var, where the result is stored.
- <sql:update> – Executes INSERT, UPDATE, or DELETE statements. Attributes: dataSource, sql, var.
- <sql:param> – Sets a parameter value for prepared statements; it has a value attribute.
- <sql:dateParam> – Sets a date/time parameter with attributes value and type (DATE, TIME, TIMESTAMP).
- <sql:transaction> – Groups multiple SQL operations in a single transaction. Attribute dataSource identifies the data source.
53. What are JSP custom tags?
Custom tags are user-defined tags that encapsulate reusable logic. A developer can define their own tags, tag attributes, and bodies. A custom tag is constituted from: a tag handler class, (either a classic tag handler or a SimpleTag), a descriptor, or a Tag Library Descriptor (TLD), and a usage taglib directive. Custom tags establish more reuse and are maintainable.
54. What are the components of a custom tag?
A custom tag typically consists of:
- Tag handler class – A Java class that implements either the Tag, BodyTag, IterationTag, or SimpleTag interfaces to establish the behaviour of the custom tag.
- Tag Library Descriptor (TLD) – An XML file that defines a custom tag name, and its attributes, and tag handler class.
- Tag library – A collection of custom tags contained in a jar that would allow for a taglib directive in the JSP to declare the usage of the custom tag.
55. When should you use JSP custom tags?
Custom tags would be used when you need reusable presentation logic that is either not provided for through the standard tags or JSTL. Custom tags allow for hiding complicated Java code from your JSP pages, provide cleaner separation of concerns, and are more readable for your JSP pages. Custom tags would be considered when needing to perform custom formatting, integrate with proprietary APIs, or any other complicated iteration that JSTL may not have been designed to handle easily.
56. What is the difference between JSTL and custom tags?
JSTL is based on a set of standardised tags defined by the Java EE specification; it is for common tasks, such as iterating, conditionals, formatting, and accessing databases. Custom tags are tags defined by the user and can have any functionality that is needed by an application. The major difference is JSTL tags are pre-built and portable, while custom tags are unique to your application, and you will need a handler class and a TLD for each.
57. What is a JSP filter, and how is it used?
A filter is an object that can intercept a request and response in a web application. The filter is configured in the web.xml file of the application and can do things like process a request-response cycle for authentication, logging, adding compression, or modifying the request/response headers. In a JSP application, filters will typically wrap a JSP or servlet; a developer can implement the javax.servlet.Filter interface and override the doFilter() method to process the request, call chain.doFilter() to pass control to another filter or resource, and optionally process the returned response.
58. How can you use EL with JSTL?
One can utilize Expression Language (EL) inside attributes defined by JSTL tags to reference variables. 
<c:set var="userName" value="${param.username}" />
<c:if test="${not empty sessionScope.user}">Welcome, ${sessionScope.user.name}</c:if>
For instance, the EL expressions ${param.username} and ${sessionScope.user.name} retrieve parameters from a request scope and attributes from a session scope, respectively. In summary, EL is intended to evaluate the logical condition and return the output value more concisely and intuitively to JSTL tags.
Advanced JSP Interview Questions
In this last section, we will review Advanced JSP Interview Questions and Answers that address MVC architecture, exception handling, internationalization (i18n), JSTL SQL tags, and good security practices. This advanced section is intended for senior developers as a tool to demonstrate mastery of JSP and enterprise-level web application development.
59. What is the MVC architecture in JSP?
The Model-View-Controller (MVC) architecture is a design pattern that separates the application into the model (business – data layer), the view (presentation layer), and the controller (coordination). In a Java web application, the model is associated with java classes and services, a controller is a servlet that receives a request, gets the model data, and forwards a response to the view. The view is a JSP that generates the HTML to the client. Separation of concerns with MVC architecture helps with closer concerns i.e. UI code can be separated from business logic, and the coordination part does a good job at orchestrating.
60. How do you handle exceptions in JSP?
Exceptions can be handled in several ways:
- Page‑level exception handling by using the errorpage attribute. In your main page, you will specify <%@ page errorPage=”error.jsp” %>. You should then create error.jsp page with the syntax <%@ page isErrorPage=”true” %>. In this method, you can use an implicit exception object in your JSP that can tell you what went wrong.
- Try-catch blocks inside your JSP. You can catch your exceptions around specific code blocks and throw your own message to display to the users.
- Application-level handling to add entries to your web.xml. You can map a specific exception to an error page or a response code of an HTTP exception with an error page. Error pages can also access the erroneous request via pageContext.errorData.
61. How do you handle exceptions thrown by the service() method?
The _jspService() method wraps the body of the JSP. All unhandled exceptions thrown from this method will propagate as ServletException or IOException. This can be handled by:
- Declare mappings in web.xml for the Throwable, ServletException, or exceptions you want to have it invoked.
- Fill try-catch blocks around your code and manage the exceptions accordingly.
62. How do you use JSTL to handle exceptions?
JSTL provides the <c:catch> tag to catch exceptions of type Throwable within its body. It has a var attribute to store the exception. For example:
<c:catch var="e">
    <c:out value="${1/0}" />
</c:catch>
<c:if test="${e != null}">Exception: ${e.message}</c:if>
If an exception occurs in the body, the exception object is stored in the variable and can be tested using <c:if>.
63. How can you disable scripting elements in JSP?
To prevent the use of scriptlets and other scripting elements, you can configure the jsp-property-group in the deployment descriptor (web.xml) with <scripting-invalid>true</scripting-invalid>. Adding this inside web.xml causes the container to throw a 500 error if a JSP contains scriptlets, thereby enforcing scriptlet‑free.
64. How can you disable or ignore EL evaluation?
There are two ways to disable Expression Language evaluation:
- Add isELIgnored=”true” in the page directive. This will ignore all EL expressions in the page, and they will be sent to the client as literal text.
- Use a <jsp-property-group> in web.xml with <el-ignored>true</el-ignored> to disable EL for a group of pages. When disabled, ${…} expressions are not evaluated.
65. What are JSP EL implicit objects, and how do they differ from JSP implicit objects?
EL implicit objects are predefined variables accessible within EL expressions. They include:
- pageScope, requestScope, sessionScope, applicationScope – Maps for scoped attributes.
- param, paramValues – Access request parameters and multi‑valued parameters.
- header, headerValues – Access request headers.
- cookie – Access cookies by name.
- initParam – Servlet context initialization parameters.
- pageContext – Provides access to the page context for advanced properties
 
These differ from JSP implicit objects (request, response, out, session, etc.) because they are specific to EL and return Maps or values rather than Java objects.
66. What is internationalisation (i18n) and localisation (l10n) in JSP?
Internationalisation (i18n) is the process of designing applications to support multiple languages and regions. Localisation (l10n) is the process of adapting the application for a specific locale (translation, formatting of dates, numbers, currencies). In JSP, JSTL’s fmt tags (<fmt:message>, <fmt:setLocale>, <fmt:formatDate>) help load resource bundles and format messages according to the current locale.
67. How do you change the locale dynamically in JSP?
The locale can be changed by:
- Using <fmt:setLocale value=”fr_FR” /> on a page to set the locale for subsequent formatting tags.
- Storing the desired locale in the session and retrieving it before using JSTL tags.
- Reading a lang parameter from the request and calling response.setLocale() or <fmt:setLocale> accordingly.
68. How do you implement session tracking if cookies are disabled?
If the browser does not accept cookies, the server can still track sessions using URL rewriting or hidden form fields. Use response.encodeURL(url) to append a jsessionid parameter to URLs. Similarly, embed the session ID in hidden form fields in POST forms. The container will automatically encode URLs when using <c:url> in JSTL.
69. What is jsp-config in web.xml, and what is its use?
The <jsp-config> element in web.xml allows you to set global properties for JSP pages, such as including a prelude (common header) and coda (footer), specifying page encoding defaults, and declaring <jsp-property-group> elements to apply properties (e.g., isELIgnored, scripting-invalid, include-prelude) to groups of JSP pages. It centralises JSP configuration. 
70. How can you upload a file using JSP?
File upload requires a form with method=”post” and enctype=”multipart/form-data”. One approach uses the Apache commons-fileupload library. A JSP (e.g., UploadFile.jsp) reads the request using ServletFileUpload and writes files to disk. The article from DataFlair demonstrates creating a DiskFileItemFactory, parsing the request into FileItem objects, and writing each file to a directory specified via a context parameter. The code checks for multipart/form-data, sets memory and file size thresholds, and saves files to a path configured in web.xml. The HTML form contains <input type=”file” name=”file” /> fields and sets the enctype accordingly.
71. Where are uploaded files stored in JSP applications?
Files are typically stored in a directory on the server specified by the developer. In the DataFlair example, a <context-param> in web.xml defines file-upload with a path (e.g., c:apache-tomcat-9.0.34webappsdata), and uploaded files are written to this directory. Alternatively, you can store files in the application’s /uploads directory or on cloud storage.
72. What is page redirection in JSP and when is it used?
Page redirection occurs when the server instructs the browser to navigate to a different URL. In JSP, you can use response.sendRedirect(url) or <c:redirect> to perform client‑side redirection. Redirection is used when you want to redirect the user to a different domain or to implement the Post/Redirect/Get pattern to avoid form resubmission.
73. How can you perform database operations in JSP using JSTL SQL tags?
Use <sql:setDataSource> to define a data source with driver, URL, user and password. Then use <sql:query> to execute SELECT statements; results are stored in a variable accessible via EL. For INSERT/UPDATE/DELETE operations, use <sql:update>. Parameters can be bound using <sql:param> or <sql:dateParam> tags. Use <sql:transaction> to group multiple operations within a transaction. 
Note: JSTL SQL tags are intended for simple demonstrations and prototyping; in production, prefer JDBC or ORM frameworks.
74. How can you perform input validation in JSP using EL or JSTL?
Input validation can be performed in JSP by checking request parameters with EL and JSTL conditions:
<c:if test="${empty param.username || empty param.password}">
  <p>Please enter username and password.</p>
</c:if>
For pattern matching or numeric checks, use functions from the JSTL Functions library (fn:length, fn:contains, etc.). However, complex validation should occur in the server-side controller or JavaBean, not in JSP.
75. What are JSP best practices for security and performance?
- Avoid scriptlets; use JSTL and EL to separate presentation from logic.
- Validate and escape input to prevent Cross‑Site Scripting (XSS) and injection attacks. Use <c:out> or Apache StringEscapeUtils to escape untrusted data.
- Use prepared statements for database queries; avoid SQL injection.
- Use the buffer attribute to improve performance and manage output flows.
- Cache frequently used data (e.g., using application scope attributes) to reduce database calls.
- Use HTTPS and secure cookies.
- Configure session timeouts and invalidate sessions on logout.
- Place JSPs under WEB-INF so they are not directly accessible.
- Compress responses using filters to reduce bandwidth.
76. How can you prevent XSS and scriptlet misuse in JSP?
To prevent XSS:
- Escape all untrusted data before inserting it into HTML using <c:out> or custom functions.
- Validate input on both client and server.
- Use content security policies (CSP) and secure headers.
 To avoid scriptlet misuse:
- Avoid embedding Java code in JSP. Use JSTL, EL, custom tags, or frameworks.
- Configure <scripting-invalid>true</scripting-invalid> in web.xml to disable scriptlets.
- Adopt MVC and move logic to controllers or beans.
77. What are the limitations of JSP technology?
While JSP remains part of the Java EE platform, it has limitations:
- Mixing Java and HTML can become messy, leading to maintenance issues.
- JSPs still compile to servlets; dynamic changes require recompilation.
- Performance may be slower than frameworks that precompile templates or use reactive architectures.
- Limited support for modern client‑side patterns (SPAs), often combined with JavaScript frameworks.
- Overuse of JSP may lead to monolithic applications. Modern frameworks (e.g., Spring Boot, JSF, Thymeleaf) often provide better separation and features.
Conclusion
For any Java developer looking to build or maintain powerful, scalable web applications, it is important you master JSP interview questions. We have discussed everything you need to know about JSP, including the basics, lifecycle, and advanced topics such as JSTL, EL, custom tags, filters, and the MVC design pattern. Don’t forget, while JSP is about writing dynamic pages, you will also need to understand the relationship between JSP, Servlets, and JavaBeans in order to present powerful, secure, efficient, and maintainable web-based solutions. 
Going through these JSP interview questions and answers as a refresher would also help solidify your understanding and confidence in coding. Whether you are interviewing for entry-level or senior developer roles, you will certainly help to distinguish yourself and demonstrate a good understanding of contemporary Java web development by understanding the following JSP topics.
JSP Interview Questions – FAQs
		
			
				Frequently Asked Questions			
							
								
					Q1. What are the top job roles available after learning JSP?
					
						 Upon completion of the course, consider applying to jobs that can include Java Developer, Full-Stack Developer (Java), Web Application Developer, Software Engineer (Java EE), and Backend Developer. The roles typically have a job description that includes developing dynamic web applications using JSP, Servlets, JDBC, or Spring. JSP is often an essential skill for Java roles at an enterprise level.
					 
				 
								
					Q2. How is the interview process for JSP-based roles?
					
						 The interview process for JSP-related roles is usually structured to have a few rounds. Once a candidate passes the initial screening, there is typically a screening process that may include doing a technical screen, a variant of a coding round, or a practical round. Following that, there may be one or more HR or behavioral interviews. The technical round often includes covering web applications and will rely on the candidate’s ability to answer interview questions related to JSP lifecycle methods, directives, EL, JSTL, and additional questions related to Servlets or databases. Real JSP project experience can increase your odds.
					 
				 
								
					Q3. Which companies hire JSP developers in India?
					
						 A wide range of companies hire JSP developers, including leading tech organizations and service-based companies such as TCS, Infosys, Wipro, Accenture, IBM, Cognizant, and Capgemini. Along with those companies, product-based startups and SaaS companies hire JSP developers to upgrade existing or maintain legacy Java web apps. These organizations may typically stipulate that applicants need to be proficient in JSP, Servlets, or Spring Boot as conditions for hire.
					 
				 
								
					Q4. What is the average salary of a JSP developer in India?
					
						 The salary of JSP developers in India varies depending on experience and location. On average, mid-level JSP developers earn between INR 4 LPA – 8 LPA. Freshers will earn around INR 3 – 4 LPA. An experienced JSP/Java EE developer working on enterprise projects can earn around INR 10-12 LPA or higher. In the international market, salaries range from USD 70,000 – 110,000 per year based on skills and work.
					 
				 
								
					Q5. How can I build a successful career as a JSP developer?
					
						 To build a successful career in JSP development, one should master core Java, Servlets, JDBC, JSTL, EL, and frameworks like Spring or Hibernate. It is good to gain hands-on experience at school by working on a capstone project, internship, or helping out with open-source applications.  You should learn modern Java technologies; keeping up with modern Java web applications and MVC will help with success in recruiting and having higher salary potential.