JSP stands for JavaServer Pages or Jakarta Server Pages. It is a server-side technology used for creating dynamic web content. In other words, JavaServer Pages (JSP) is a technology that enables developers to create dynamic and platform-independent web pages for Java web applications.
Sun Microsystems released JSP in 1999, and it is analogous to Active Server Pages (ASP) and PHP but uses the Java programming language. The JSP technology is an advanced version of Java Servlet technology.
We can say that each JSP is a servlet since it is translated into a Java servlet at runtime. In addition, we can use JSP as a view component of the server-side model-view-controller design, in which Java servlets act as the controller and JavaBeans as the model.
If you aim to appear for a JSP interview and want to revise the important JSP concepts, you have landed at the right place.
This article aims to discuss some of the most commonly asked JSP interview questions along with their answers. So, let us get started!
Top JSP Interview Questions and Answers
We shall divide the JSP interview questions into three levels, namely beginner, intermediate, and advanced.
Beginner-Level JSP Interview Questions
1. What do you know about JSP?
JavaServer Pages, abbreviated as JSP, is a server-side language used for creating dynamic and platform-independent web pages in the form of HyperText Markup Language (HTML). This technology enables developers to embed Java code into HTML pages by using JSP tags, where most of them start with ‘<%’ and end with ‘%>’.
2. Can you explain the features of JSP?
The following are the salient features of JSP:
- JSP is a tag-based programming language that extensively uses tags in code, which in turn improves the readability of the code.
- There are nine implicit objects in JSP, and we can use them directly in our code without writing any other additional code to access them.
- It separates business logic (Java code) from presentation logic (HTML code).
- JSP is secure, platform-independent, and dynamic.
- It has all features of Java servlets since it is an extension of the Java Servlet technology.
3. Explain the life cycle of JSP.
The life cycle of JSP starts with its creation and ends with its destruction. It is analogous to the life cycle of a servlet but involves an additional step required to compile a JSP into a servlet. There are seven steps involved in the life cycle of JSP, as explained below:
- Translation of a JSP to servlet: It is the JSP life cycle’s first step. The JSP engine translates the JSP file ( say, test.jsp) into the server file (say, test.java).
- JSP Compilation: The server file (test.java) is compiled into a class file (test.class).
- Classloading: The servlet class loaded from the JSP source is loaded into the container.
- Instantiation: Here, an instance of the Servlet class is generated. A container is responsible for managing multiple instances by responding to requests.
- Initialization: After the generation of the Servlet instance from JSP, the jspInit() method is called. It is used only once during the life cycle of JSP.
- Request Processing: The _jspService() method serves the requests raised by JSP. This method takes parameters as request and response objects, i.e., HttpServletRequest and HttpServletResponse. We cannot override this method.
- JSP Cleanup: When the JSP is removed from use by a container, it represents the destruction phase of the JSP life cycle. The jspDestroy() method helps to remove JSP from the use by a container. In addition, we can override this method to perform cleanup, like closing files, releasing database connections, etc.
4. Can you define a scriptlet in JSP with its syntax?
A scriptlet in JSP can contain any number of Java language expressions, statements, and method or variable declarations, that are valid for the scripting language used in a page. The syntax of a JSP scriptlet is given below:
<% code fragment %>
5. List out some advantages of JSP.
The following are the key benefits of using JSP:
- JSP offers better performance and high scalability since it enables developers to embed dynamic elements in HTML pages.
- It is built on top of the Java Servlet technology. Therefore, JSP also has access to all enterprise-level Java APIs, including EJB, JDBC, and JAXP.
- JavaServer Pages are easy to maintain since the business logic and presentation logic are maintained separately.
- We can access standard objects and actions using JSP containers.
- It becomes easier for developers to connect websites to a database and read and write data from and to the database.
6. What do you understand from JSP comments?
JSP comments are statements or text that the JSP container should ignore at the compile-time. We use these comments if we want to hide a specific part of the JSP page.
7. How will you write comments in JSP?
The syntax for writing comments in JSP is as follows:
<%-- Comment --%>
8. What do you understand about implicit objects in JSP?
Implicit objects in JSP are Java objects and are also referred to as predefined variables . The JSP container automatically created these implicit objects, making them available to developers so that there is no need to create them explicitly. They are accessed using standard variables and are available only within the _jspService method. In addition, the JSP container parses the implicit objects and inserts them into the generated servlet code.
9. List out JSP implicit objects with their types.
JSP has nine implicit objects by default. The following table represents JSP implicit objects with their types.
10. Explain different action elements in JSP.
JSP action elements or action tags control the flow between pages. Each action tag or element performs a specific task. The following are the action elements or action tags in JSP:
- <jsp:useBean>: We can use this element to use JavaBeans on the JSP page. It enables us to invoke a bean easily.
- <jsp:include>: Using this action element, we can include a JSP file into another file.
- <jsp:setProperty>: We can use this action element to set the property of the bean. However, it is important to define the bean first before setting the property.
- <jsp:getProperty>: Using this action element, we can get the property of the bean.
- <jsp:forward>: It forwards a request to another JSP or any static page.
- <jsp:plugin>: This element lets us introduce Java components into JSP.
- <jsp:param>: It is the child object of the plugin object and contains one or more actions to provide additional parameters.
- <jsp:body>: It defines the body of dynamically-defined XML.
- <jsp:attribute>: It defines the attribute of dynamically-defined XML.
- <jsp:text>: This action element enables us to write template text in JSP pages and documents.
- <jsp:output>: It specifies the DOCTYPE declaration or XML declaration of JSP.
11. List out directive tags in JSP.
The following are the three directive tags in JSP:
- <%@page…%>: This tag defines page-dependent attributes, such as error page, scripting language, and buffering requirements. Also, we can provide instructions to the container about the current JSP page.
- <%@ include ... %>: It includes a file during the translation phase. We can use this directive to include one file in another. The included file can be JSP, HTML, text files, etc.
- <%@ taglib ... %>: With this directory tag, we can define a tag library with the ‘tag library’ prefix to use in JSP.
12. List out different attributes of the page directive.
The following are the 13 attributes of the page directive:
13. List out and explain different scripting elements in JSP.
JSP scripting elements are enclosed within ‘<%’ and ‘%>’ tags. The JSP engine processes the code present in these tags during the translation of the JSP page. Any other code on the JSP page is plain text or HTML code. The following are the scripting elements in JSP:
- <% Java Code %>: It is a scriptlet tag and enables us to embed Java code inside the JSP page.
- <%! Declaration %>: It is a declaration tag, and we can declare static members, instance variables, and methods inside it.
- <%= Java Expression =%>: It is an expression tag, allowing us to print any Java language expression provided as an argument to the out.print() method.
14. Explain what is hidden and output comments in JSP.
The JSP comment is referred to as the hidden comment, whereas the HTML comment is called the output comment. The output comment is visible to clients since it appears in the output. On the flip side, the hidden comment is not visible to clients since it does not appear in the output. We can use the hidden comment to hide a specific part of the JSP page.
15. What do you know about JSP Expression Language (EL)?
JSP Expression Language (EL) makes it easier for us to access the data stored in JavaBean components. Also, it simplifies the accessibility of other objects, like, a request, session, etc. JSP EL lets us create arithmetic and logical expressions using arithmetic and logical operators.
16. Explain literals in JSP.
Literals in JSP are values, such as a text string or a number, written literally as a part of the code. The following are the five different literals defined by the JSP Expression Language (EL):
- Floating point
17. List out JSP Expression Language (EL) operators.
The table highlights JSP EL operators with their descriptions:
|.||Access a bean property or Map entry|
|||Access a List or array element|
|()||Group, a subexpression to change its evaluation order|
|-||Negation of a value or subtraction|
|div or /||Division|
|mod or %||Modulo|
|eq or ==||Test for equality|
|ne or !=||Test for inequality|
|lt or <||Test for less than|
|gt or >||Test for greater than|
|le or <=||Test for less than or equal|
|ge or >=||Test for greater than or equal|
|and or &&||Test for logical AND|
|or or ||||Test for logical OR|
|not or !||Unary Boolean complement|
|Empty||Test for Empty variable values|
Intermediate-Level JSP Interview Questions
18. Explain the difference between Include Directive and Include Action.
The following table describes the key differences between Include Directive and Include Action:
|Include Directive||Include Action|
|The include directive (@include) is processed at the translation time.||Include action() is processed when the request arrives for processing.|
|It can use both relative and absolute paths.||It can only use the relative path.|
|Include directive can only include the contents of the resource, i.e., HTML or CSS files, and not the dynamic content.||It processes dynamic resources and adds the result to the calling JSP.|
|We cannot pass any other parameters, like request, response, or configuration, with the included directive.||We can set parameters using the <jsp:param> tags.|
|Syntax: <%include file = “file_name“%>||Syntax: <%JSP:include page = “file_name“%>|
19. Is JSP technology extensible?
Yes, the JSP technology is extensible by developing tags and custom actions encapsulated in tag libraries.
20. Explain the request object and list out its methods.
The request object in JSP is implicit. It is an instance of the class that implements the javax.servlet.http.HttpServletRequest interface. We can retrieve the values the client transfers to the server via the HTTP request using this object.
A web container creates a new object whenever a client requests a page. In addition, we can retrieve the HTTP header information, including cookies , form data, parameters server name, server port, etc.
Methods of the JSP request objects are:
- request.getParameter(String name)
- request.getParameterValues(String name)
- request.getHeader(String hdr)
- request.setAttribute(String, object)
21. Explain the response object.
Like the request object, a response object is also an implicit object in JSP. It is an instance of the class that implements the javax.servlet.http.HttpServletResponse interface. It enables developers to add new cookies, HTTP status codes, etc. A web container creates a response object for every request of a client. Generally, the response object is used to manipulate a response, such as redirecting a response to any other resource, sending errors, etc.
22. List out implicit objects in JSP Expression Language (EL).
The following are the implicit objects in JSP Expression Language (EL):
23. Explain the difference between JSP and Servlet.
The below table highlights the key differences between JSP and Servlet:
|JSP is a HTML-based code.||Servlet is Java code.|
|In the MVC pattern , JSP serves as the view component.||It acts as the controller in the MVC design pattern.|
|JSP is relatively slower than servlet since it includes an additional step of translating JSP to Java code and then compiling it.||Servlet is faster than JSP.|
|The service() method in JSP cannot be overridden.||The service() method in Servlet can be overridden.|
|In JSP, the presentation logic and the business logic are separated.||We need to implement everything in a single servlet file, like business logic and presentation logic.|
|Session management is automatically enabled in JSP.||We have to enable session management explicitly.|
24. Explain the difference between ASP and JSP.
Both Active Server Pages and JavaServer Pages serve the same purpose of developing dynamic content. The following table highlights the key differences between ASP and JSP:
|Active Server Pages||JavaServer Pages|
|Active Server Pages enables developers to create dynamic web pages.||JavaServer Pages enables developers to dynamically create web pages based on HTML, XML, and other types.|
|It is not platform-independent and not free to use.||It is platform-dependent and free to use.|
|ASP does not ensure memory leak protection.||JSP ensures memory leak protection.|
|It provides poor security as compared to JSP.||It provides better security.|
|File extension of ASP is .asp.||File extension of JSP is .jsp.|
25. Differentiate between JSP and PHP.
The following table describes the difference between JSP and PHP:
|JSP stands for JavaServer Pages, and it is a server-side programming technology for creating dynamic web content.||PHP stands for HyperText Preprocessor, and it is a server-side scripting language for managing web content.|
|We can define custom tags in JSP.||It does not allow custom tags.|
|JSP requires a servlet container like Apache Tomcat to run.||PHP has its own CGI engine to run.|
|It requires complex and more lines of code.||It is a simple language and requires fewer lines of code.|
26. Explain the difference between client-side validation and server-side validation.
The following table highlights the differences between client-side validation and server-side validation:
|Client-side Validation||Server-side Validation|
|Client-side validation is generally used to validate and display field-level errors.||Server-side validation is used to validate and display form-level errors.|
|Client-side validation helps prevent a round trip of invalid data from client to server and back.||Server-side validation helps prevent the insertion of invalid data into databases and protects against malicious users.|
27. Can you tell the difference between ServletContext and PageContext?
ServletContext: It shares the information about the container in which the servlet is running. Each web application has only one ServletContext, and we can set its parameters in the web application descriptor.
PageContext: It provides the Servlet information about the currently managed request and contains information about the request, response object, session, and a reference to the web application’s ServletContext.
29. Explain the difference between JSPWriter and PrintWriter.
The differences between JSPWriter and PrintWriter are:
- The JSPWriter object has the same methods as the java.io.PrintWriter class but has some additional methods that deal with buffering.
- The print method of JSPWriter does not throw IO exceptions, whereas PrintWriter’s print method throws exceptions.
- JSPWriter uses BufferWriter and PrintWriter internally, whereas PrintWriter does not.
30. How does JSP handle data processing?
JSP handles data processing using the following four methods:
- getParameter(): This method enables us to retrieve the value of the form parameter.
- getParameterValues(): One can use this method to retrieve all the values of a parameter that appears more than once. For example, checkbox.
- getParameterNames(): This method returns the names of parameters.
- getInputStream(): It is used to read the binary data sent by a client.
31. Explain cookies in JSP.
Cookies are text files created on the client machine and used for various information tracking purposes. These files contain information about web searches or sites explored using a browser, time of visit, date, and IP address. Moreover, cookies are set in the HTTP header. If a browser is configured to store cookies, it will store the information until expiration.
32. List out and describe all methods of cookies in JSP.
The following are the methods of cookies:
- public void setDomain(String pattern): To set the domain to which the cookie applies.
- public String getDomain(): To get the domain to which the cookie applies.
- public void setMaxAge(int expiry): To specify the time that should elapse before the cookie expires. The cookie will last for the current session only if no time is set.
- public int getMaxAge(): To get the maximum age of the cookie in seconds. By default, it returns -1, indicating that the cookie will persist till the browser shuts down.
- public String getName(): To get the name of the cookie.
- public void setValue(String newValue): To set the value associated with the cookie.
- public String getValue(): To get the value associated with the cookie.
- public void setPath(): To set the path to which the cookie applies.
- public String getPath(): To get the path to which the cookie applies.
- public void setSecure(boolean flag): To set the boolean value, indicating whether the cookie should be sent over the secured connections or not.
- public void setComments(String purpose): To specify the comment describing the cookie’s purpose.
- public String getComment(): To get the comment describing the cookie’s purpose. If there is no comment, it returns null.
33. How do you set cookies in JSP?
There are various steps involved in setting cookies, and they are described below:
- Creating a cookie object: To create a cookie object, we need to call a cookie constructor with a cookie name and cookie value. Both the cookie name and cookie value are strings.
Cookie cookie = new Cookie("key", "value");
- Setting the maximum age: After creating a cookie object, set the maximum age for the cookie. Use the setMaxAge() method to specify how long a cookie should remain valid. The following code sets the cookie for 24 hours:
- Sending the cookie into the HTTP response header: To add cookies into the HTTP response header, we need to use the response.addcookie() method.
34. How to delete cookies in JSP?
It is quite easy to delete cookies in JSP. We need to follow the steps mentioned below to delete cookies in JSP:
- Firstly, read the existing cookie and store it in a cookie object.
- Use the setMaxAge() method to set the age of the cookie as zero.
- After setting the age, send the cookie back into the response header.
Advanced-Level JSP Interview Questions
35. How can you forward a request to another resource?
We can forward a request to another resource using the <jsp:forward> action . The <jsp:forward> action has a page attribute that allows us to specify the target page.
36. Can we extend another Java class in JSP?
Yes, we can extend another Java class in JSP using <%@include page extends = “class_name”%>.
37. Can you explain the use of the <jsp:useBean> tag?
We use the <jsp:useBean> tag to locate or instantiate the bean class. It searches for an existing object depending on its id and scope variable. Also, this tag creates a new object if the existing object is not available.
38. What are filters in JSP?
Filters in JSP Java classes are primarily used for two different purposes:
- To intercept requests from a client before they access a resource.
- To manipulate responses from the server before they are sent to the client.
Also, filters in JSP are used to authenticate user credentials and perform data encryption techniques. We can create and implement a filter interface in JSP using the javax.servlet class.
39. List out different filters in JSP.
The following are the various filters in JSP:
- Data Compression Filters
- Image Conversion Filters
- Authentication Filters
- Encryption Filters
- Logging and Auditing Filters
- Tokenizing Filters
- Filters triggering resource access events
- MIME-TYPE Chain Filters
- XSL/T Filters
40. Explain a servlet filter and list out its methods.
A servlet filter is a Java class that implements the jsvax.servlet.Filter interface. This interface defines three different methods, as listed below:
- public void doFilter(ServletRequest, ServletResponse, FilteChain)
- public void init(FilterConfig filterConfig)
- public void destroy()
41. What do you understand about JSTL?
JSTL stands for JavaServer Pages Standard Tag Library. It is a collection of custom tag libraries providing common functionalities for web development. It offers tags for manipulating XML documents, supports common structural tasks, such as conditionals and iteration, provides SQL tags and internationalization tags.
42. Explain the types of JSTL tags.
The following are the five different types of JSTL tags:
- Core Tags: JSTL core tags provide URL management, variable support, and flow control. All core tags have the prefix ‘c’. The syntax to include the JSTL core library in JSP is given below:
<%@ taglib prefix = "c" uri = "https://java.sun.com/jsp/jstl/core" %>
- Formatting Tags: JSTL formatting tags are used for formatting and displaying text, date, time, and numbers for internationalized websites. All formatting tags have the prefix ‘fmt’. The syntax to include the JSTL formatting library in JSP is given below:
<%@ taglib prefix = "fmt" uri = "https://java.sun.com/jsp/jstl/fmt" %>
- SQL Tags: JSTL SQL tags support the interaction with relational databases, such as Microsoft SQL Server, Oracle, and MySQL. All SQL tags have the prefix ‘sql’. The syntax to include the SQL library in JSP is given below:
<%@ taglib prefix = "sql" uri = "https://java.sun.com/jsp/jstl/sql" %>
- XML Tags: JSTL XML tags support the creation and manipulation of XML documents. All XML tags have the prefix ‘x’. The syntax to include the XML library in JSP is given below:
<%@ taglib prefix = "x" uri = "https://java.sun.com/jsp/jstl/xml" %>
- JSTL Functions: JSTL offers a plethora of functions, most of which are used to manipulate a string. All JSTL functions have the prefix ‘fn’. The syntax to include the JSTL Functions library in JSP is given below:
<%@ taglib prefix = "fn" uri = "https://java.sun.com/jsp/jstl/functions" %>
43. Explain different JSTL Core tags.
The following are the different JSTL Core Tags:
- <c:out>: It displays the result of an expression and works similarly as the ‘ <%=%> ’ tag works.
- <c:set>: It evaluates an expression and uses its result to set the value of a java.util.Map object.
- <c:remove>: It removes a variable from a specified scope or from the first scope where the variable is found.
- <c: catch>: It catches any throwable occurring in its body and exposes it optionally.
- <c:if>: It is a conditional tag and evaluates its body if the specified condition holds true.
- <c:choose>: It is analogous to the Switch statement in Java and allows us to choose between multiple alternatives.
- <c:when>: It is the subtag of <c:choose> and runs if the specified condition holds true.
- <c:otherwise>: It is the subtag of <c:choose> that follows <c:when> and runs only if all the prior conditions evaluate to false.
- <c:import>: It provides all functionalities of the <include> action and allows the inclusion of absolute URLs.
- <c:forEach>: It iterates over a collection of objects.
- <c:forTokens>: It breaks a string into tokens and iterates through each token.
- <c:param>: It adds a parameter to the URL of the ‘import’ tag.
- <c:redirect>: It redirects to a new URL.
- <c:url>: it creates a URL with optional query parameters.
44. Explain different JSTL Formatting Tags.
The following are various JSTL formatting tags:
- <fmt:formatNumber>: It formats numbers, percentages, and currencies.
- <fmt:parseNumber>: It parses the string representation of numbers, percentages, and currencies.
- <fmt:formatDate>: It formats the date and/or time depending upon the supplied pattern and styles.
- <fmt:parseDate>: It parses the string representation of a date and/or time.
- <fmt:bundle>: It makes a specified bundle available to all <fmt:message> tags occurring between <fmt:bundle> and </fmt:bundle>.
- <fmt:setLocale>: It stores the given variable in the locale configuration variable.
- <fmt:setBundle>: It loads a resource bundle and stores it in the bundle configuration variable.
- <fmt:timeZone>: It specifies the time zone for time formatting and nesting actions in its body.
- <fmt:setTimeZone>: It stores the given time zone in the zone configuration variable.
- <fmt:message>: It displays an internationalized message.
- <fmt:requestEncoding>: It specifies the encoding type the forms use to post the data back to the web application.
45. Explain different JSTL SQL tags.
The following are the JSTL SQL tags:
- <sql:setDataSource>: It sets the data source configuration variable or stores the data-source information in a scoped variable. We can use this information as the input to other JSTL database actions.
- <sql:query>: It executes the SQL query specified in its body and saves the result in a scoped variable.
- <sql:update>: It executes SQL statements, like INSERT, DELETE, and UPDATE, that do not return data.
- <sql:param>: It is used as a nested action for <sql:query> and <sql:update> to provide a value for a value placeholder.
- <sql:dateParam>: It is used as a nested action for <sql:query> and <sql:update> to provide a date and time value for a value placeholder.
- <sql:transaction>: It groups <sql:query> and <sql:update> tags into transactions. This tag can include as many <sql:query> and <sql:update> tags as statements to form a single transaction.
46. Explain different JSTL XML tags.
The following are the various JSTL XML tags:
- <x:out>: It displays the result of an XPath expression and works similarly to the <%=%> tag.
- <x:parse>: It parses the XML data specified using an attribute or in the tag body.
- <x:set>: It sets a variable to an XPath expression’s value.
- <x:if>: It evaluates the test XPath expression. If the expression holds true, it processes the body of <x:if>, otherwise, it ignores the body.
- <x:forEach>: It iterates over nodes in an XML document.
- <x:choose>: It works like a Java Switch statement, allowing us to choose among multiple alternatives. It has <x:when> and <x:otherwise> tags, whereas the switch statement has multiple case statements.
- <x:when>: It is the subtag of <x:choose> and executes its body if the specified condition holds true.
- <x:otherwise>: It is the subtag of <x:choose> and executes its body if all the previous conditions evaluate to false.
- <x:transform>: It applies an XSL transformation on a XML document.
- <x:param>: We can use it with <x:transform> to set a parameter in the XSL stylesheet.
47. Explain different JSTL Functions.
The following is the list of JSTL functions:
- fn:contains(): It verifies whether a string contains the specified substring.
- fn:containsIgnoreCase(): It ignores the case of the string while checking whether the string has the specified substring.
- fn:endsWith(): It checks whether the string ends with the specified substring or not.
- fn:escapeXML(): It escapes characters that can be interpreted as XML markup.
- fn:indexOf(): It returns the index within a string of a specified substring.
- fn:join(): It concatenates all the elements of an array into a string.
- fn:length(): It returns the number of characters in a string.
- fn:replace(): It replaces all string occurrences with the specified string.
- fn:split(): It splits a string into multiple substrings.
- fn:StartsWith(): It determines whether an input string starts with the specified substring.
- fn:substring(): It returns a subset of a string specified by the start and end indices.
- fn:substringAfter(): It returns a subset of a string after the specified substring.
- fn:substringBefore(): It returns a subset of a string before the specified substring.
- fn:toLowerCase(): It converts all characters of a string to lowercase.
- fn:toUpperCase(): It converts all characters of a string to uppercase.
- fn:trim(): It removes white spaces from the beginning and end of a string.
48. How do you pass the control from one JSP page to another?
We can pass the control from one JSP page to another using:
- The response.sendRedirect method.
- The RequestDispatcher object‘s forward method.
49. Why does the ‘_jspService()’ method start with an underscore (‘_’)?
The JSP container automatically defines the _jspService() method. We cannot override this method like other methods, such as jspInit() and jspDestroy. The methods that can not be overridden typically begin with an underscore (‘_’). Since we cannot override the _jspService() method, we begin it with an underscore.
50. How is JSP scripting disabled?
We can disable JSP scripting by setting the scripting-invalid element of the deployment descriptor to true. The scripting-invalid element is the sub-element of the jsp-property-group . The syntax for disabling JSP scripting is given below:
<jsp-property-group> <url-pattern>*.jsp</url-pattern> <scripting-invalid>true</scripting-invalid> </jsp-property-group>
JavaServer Pages is a widely used server-side technology for creating dynamic web content. It offers high scalability and good performance since developers can embed dynamic elements into HTML pages. We have covered many significant and frequently asked JSP interview questions with their detailed answers. You can go through these questions before appearing for your next interview.
Also, feel free to share any other JSP-related questions that you have come across during your interviews in the comments section below.
People are also reading: