JSP Interview Questions And Answers [Updated 2021]

This tutorial provides  a complete list of JSP interview questions and answers with explanations to help you in your preparation:

In an attempt to create interactive web pages, Common Gateway Interface (CGI) was introduced, wherein data was sent back and forth between server and application using HyperText Transfer Protocol (HTTP), primarily to connect legacy information systems like databases to web servers.

This process had many shortcomings like overhead on memory to load CGI programs during each page load, no mechanism of caching a data between page loads, and taking too much time between the requests and response. This lack gave birth to the invention of server-side technologies such as Java Server Pages (JSP).

JSP Interview Questions

What Is JSP

JSP is an extension of Java Servlet that has access to Java API, implicit objects, and custom tags into HTML pages to create dynamic web content.

Java Server Pages (JSP) is a web-based technology that creates dynamic and interactive web content. They are created by inserting Java code in HTML as well as XML pages. JSP can access the entire Java API, which is an extended Servlet class that extends server capabilities and reacts to incoming requests.

To make web pages dynamic, Common Gateway Interface (CGI) were used, JSP over-performs CGI by allowing dynamic elements into HTML pages instead of separate CGI files. JSP code is compiled before it is being processed by the server, unlike CGI/Perl where the server needs to load interpreter and target script on each page request.

JSP has the advantage of Java APIs access that includes JDBC, EJB, JNDI, JAXP.

Suggested reading =>> JDBC Interview questions and answers

Frequently Asked JSP Interview Questions

Q #1) What is Java Server Pages (JSP)?

Answer: JSPs are server-side web-based technology for dynamic and interactive web content. It is Java code inside HTML or XML pages, an extension to Servlet with access to Java API, implicit objects, and custom tags.

Q #2) Can you explain the meaning of the dynamic web page?

Answer: A dynamic web page is interactive or responsive to visitor’s input values or time of the day, time zone, viewer’s native language.

They are of two types,

  • Client-side scripting such as HTML5, CSS3, JavaScript, JQuery, AJAX, Action Script, VB Script changes DOM elements or data dynamically.
  • Server-side scripting such as ASP, JSP, PHP, ASP.NET, ColdFusion, Java, Ruby, Perl, and Python that runs on the webserver and delivers dynamic contents by responding to client requests via HTTP.

dynamicwebpage

Q #3) Explain Server-side technology with examples.

Answer: Server-side technologies range from server-side scripting languages, database management systems, web server software such as Apache, IIS, node.js, tomcat. Server-side scripting languages like ASP, PHP, ColdFusion, Python, or JSP are used for developing dynamic web pages that can be accessed through state-less Internet protocol such as HTTP, FTP, SMTP, or Telnet.

The client machine sends the client’s request to the server, then the server verifies and executes the file and its embedded scripts, and formats resulting files and sends it to the client. The response is displayed on the client via browsers like Chrome, Mozilla, Internet Explorer, Opera, or Safari.

Q #4) What are features of JSP that make it an essential web-based technology?

Answer: The features are listed below:

  • Create interactive websites.
  • Makes it easy-to-read user input data and display server response.
  • Use of implicit objects into the web page directly.
  • Use of Java code into HTML pages through JSP.
  • Makes database connectivity simple.
  • Visitors can be tracked using Session, Application, or Cookies on the JSP page.
  • Easy to learn and code.

Q #5) Differentiate between JSP and Servlet.

Answer: The following table enlists the differences:

ServletJava Server Page
Servlet is Java code, is hard to code than JSPJava Server Page is tags in HTML page, easy as it is Java in html page.
Servlet plays as controller role in MVC approachJSP plays as view in MVC approach
In Servlet, service() method can be overriddenIn JSP, service() method cannot be overridden.
Session management is not enabled by defaultSession management is automatically enabled
In Servlet, business logic and presentation logic are implemented in single file.In JSP business logic is separated from presentation logic with help of JavaBeans
Modification of Servlet involves reloading, recompiling and restarting the server hence is time consuming.JSP modification is fast as it needs only refresh the page.

Q #6) Explain the Java Server Page Life Cycle.

Answer: JSP Life cycle, which has jspInit(), _jspService() and jspDestroy() methods consists of following phases:

  • Translation & compilation of JSP page: The first step is the conversion of the JSP page into a Java servlet file during the translation phase, validates syntax, directives, actions, and tag libraries used in the JSP page. Servlet is compiled into a servlet class file.
  • Class Loading & Execution phase: The compiled servlet class is loaded into the JSP container. Multiple instances of this class are managed by the container for requests and other events internally jspInit() and jspDestroy() methods in JSP Page interface. Another interface HttpJspPage contains _jspService() method. jspInit() method called only once initially after the instance was created.
  • Initiation: During initiation, jspInit() method is called once initially after the instance has been created, internally initializes instance variables such as java.util.Date() object, initialize database connections, open files, and create lookup tables internally.
  • Execution of _jspService(): For every JSP requests and responses _jspService() method is called for execution. This method cannot be overridden as it is implemented implicitly.
  • Execution of jspDestroy(): Finally jspDestroy() method gets executed when JSP page is destroyed, and garbage is collected.

JSP Life cycle

Q #7) What are the differences between ASP and JSP?

Answer: JSP and ASP both are used for developing dynamic web content. The basic difference between these two technologies are listed below:

Active Server Pages (ASP)Java Server Pages (JSP)
ASP is proprietary server side technology from Microsoft which is interpreted, usually implemented on windows operating systemJSP is open source server side technology from Oracle which is compiled at runtime, usually implemented on Linux operating system.
Developer with visual basic language knowledge can create Active server pages easily.Developer with Java knowledge can create Java server pages easily.
ASP can be connected to database via ADO and supports MS SQL database.JSP can be connected to any database with the help of respective libraries.
ASP supports mainly Microsoft IIS server.JSP are usually ran over JBoss, IBM app servers, Apache Tomcat or any Linux based web servers

Q #8) Differentiate between JSP and PHP.

Answer: JSP and PHP are both server-side languages with the following differences:

PHPJSP
PHP stands for Hypertext Preprocessor, is an open source server side scripting language with huge community and libraryJSP stands for Java Server pages , an open source server side programming language to support for web pages with dynamic content.
It supports for Simple, cross-platform, powerful for small or medium sized web development.It has access to Java API, internally converted into Servlet and compiled as java classes.
PHP does not support custom tagsJSP allows custom tags
It runs on its own CGI engine.Require servlet containers like Apache Tomcat
web hosting for web pages developed using php is cheapIt can have very complex code, making difficult to understand.

Q #9) Can you explain the MVC model and the use of JSP in it?

Answer: Model View Controller or MVC is a design pattern that separates data, business logic, and presentation logic. Model is the state of application representing business logic, Controller is a middle portion of view and model contains data, whereas View is a user interface or presentation layer.

A user sends the request from the browser present on the client machine, via the user interface or presentation layer of the JSP page. JSP page connects JavaBean which contains business logic and exchanges requests and response using the HTTP protocol. The response is sent back to the browser that contains status information and response content.

Q #10) What are the implicit objects used in JSP?

Answer: Following are the list of implicit objects available for use:

ObjectTypeUse in JSP
OutJspWriterOut is used for writing any data to the buffer, JspWriter object is used in JSP page
RequestHttpServletRequestRequest is created by each JSP request by web container, request information contains parameters, header information, server name, remote address, server port, content type and character encoding
ResponseHttpServletResponseResponse is used to add or update response as redirect response to another resource or send an error in case redirect does not work.
ConfigServletConfigConfig object like ServletConfig used in order to get initialization parameters from web.xml
ApplicationServletContextServletContext is an application instance works as config object as well get, set or remove attribute from application scope.
SessionHttpSessionSession object is used for get, set or remove attribute or get session information.
PageContextPageContextPageContext object is used to get, set or remove attribute from page, request, session and application objects.
PageObjectPage are assigned to reference of auto generated servlet class.
ExceptionThrowableException are objects from java.lang.Throwable class, used to print exception in error page.

Q #11) List the differences between include directive and include action tag.

Answer: Following points make include directive and include action unique from each other:

Include DirectiveInclude Action
Include directive (@include) is processed at translation time, can use to include a file at either relative path or absolute path.Include action (< jsp:include>) is processed at the time request arrives for processing, can use file present at the relative path.
They may include contents of resource such as HTML or CSS file but does not process dynamic resources.They process dynamic resource adding results to calling JSP page.
Along with include directive, parameters such as request, response or configuration could not be passed.We can pass another parameters along with include action.
To include file to JSP for include directive, request or response object cannot be passed to calling JSP.Request or response object can be passed in include action.
include directive are applied to file attribute in order to specify resource included.include action is applied to page attribute in order to specify included resource.

Q #12) Explain directives used in Java Server Pages.

Answer: JSP directives acts as global information/instructions about an entire JSP page, give directions to the container to convert JSP to servlet code, in the translation phase, and certain aspects of JSP processing. It can have comma-separated attributes in key-value format. In JSP, directive is described in <% @ %> tags.

There are three types of directives:

  • Page directives
  • Include directives
  • Taglib directive

Q #13) Explain Scriplets used in Java Server Pages.

Answer: Scriplets are the tags that are used to execute Java source code in Java Server Pages, we can embed Java executable code base such as the declaration of a variable, object manipulation, method invoking, conditional statements, and exception handling like try-catch in JSP scriplet.

<% if (actbalance<100 ) {%>
<p> maintain your account balance minimum of 100 dollars</p>
<% else if (actbalance >=100) {%>
<p>Your account is upto date</p>
<% else if (actbalance >10000) {%>
<p> Please invest your amount in fixed deposits</p> 
<% else {%>
<p> We can provide you loan if required</p>
}%>

Q #14) What are the differences between Client-Side and Server-Side Validation?

Answer: Following are the difference between client-side and server-side validation:

Client side validationServer side validation
In user interface web forms, user input values are validated at client machine, User input values are validated on server i.e. validation done on web server
Client side validation is done using JavaScript or VBScriptServer side validation is done using languages such as Java, .Net, PHP etc
Validation on client side help prevent round trip of invalid data from client to server and back Validation on server side prevents insertion of invalid data into database or protection against malicious users

Q #15) What Literals are used in JSP?

Answer: Literals used in Java server pages are as follows:

  • Boolean
  • Integer
  • Floating point
  • String
  • Null.

Q #16) List the difference between ServletContext and PageContext.

Answer: Differences between ServletContext and PageContext are given below:

  • ServletContext gives information about JSP or servlet running container. There is one servletcontext per web application, its parameters can be set up in web deployment descriptor.
  • Page Context gives JSP or servlet information about requests being handled, with information about the request and any parameters like session, response, reference to the output stream, and web application’s ServletContext.

Q #17) List the differences between JSP custom and Java Bean.

Answer: The differences are explained below:

JSP Custom TagsJavaBeans
Custom Tags is user defined JSP element can alter JSP content.JavaBeans are simple Java class in JSP pages to create dynamic web pages cannot alter JSP content.
It can simplify complex operations, requires more configurations to set up.JavaBeans are easy to set up.
Used in self contained way in both Servlet and JSP pages.JavaBeans can be defined in Servlet and then can be called in JSP or Servlet page.

Q #18) What are the differences between forward and sendRedirect?

Answer: Differences are explained below:

Forward()sendRedirect()
Redirection of pages are handled at server end and are not visible to client in forward() method.Redirection of pages are handled at client end and is visible to client, in sendRedirect() method.
forward() is faster than sendRedirect().sendRedirect() is slightly slower than forward(), as it needs two browser requests.
Original URL remains unaffected in forward()A browser understands that for sendRedirect(), it is making new request, hence original URL changes.
Original URL and requests gets repeated when resulting page in browser is reloaded.Original request or resultant URL is not repeated when browser reloads resultant URL.

Q #19) What are the attributes on page directives?

Answer: Following are the list of attributes on JSP Page Directives:

Attribute NameDescription
bufferIt indicates buffering model for output stream
autoFlushServlet output buffer behavior is controlled with this attribute
contentTypeCharacter encoding scheme related attribute
errorPageUniform Resource Locator for another JSP that reports Java unchecked runtime exceptions.
isErrorPageIndicates URL specified by JSP page’s errorPage attribute defined above.
extendsSuperclass generated Servlet must extend is specified with this attribute
importSimilar to Java classes, import attribute is used to list packages or classes for use in JSP page.
infoThis attribute is defined as a string accessed by Servlet’s getServletInfo() method,
isThreadSafeThis attribute defines threading model for Servlet
languageDeclares programming language used in JSP pages.
sessionDeclares JSP page participation in HTTP sessions.
isELIgnoredAttribute decides whether to EL expression within JSP will be ignored or not.
isScriptingEnabledWhether scripting elements are allowed for use or not can be decided by this attribute.

Q #20) Can we extend another Java class in JSP?

Answer: Yes, developer can extend another JSP using <%@ include page extends =”classname” %>.

javax.servlet.jsp.HttpJspPage interface implements when the JSP page is converted to the Servlet page. Hence, it is possible to extend another Java class for the JSP page. It is advisable to use expression language or tag library instead of java code in JSP page.

Q #21) Describe use of <jsp:usebean> tag with an example.

Answer: <useBean> tries to search an existing object based on an id and scope variable and if the object is not available, it creates the object. The code for useBean is as displayed below:

< jsp:useBean id = "myBean" class = someclass.class"/ >

Q #22) What are scope values for <jsp:usebean> tag?

Answer: In absence of scope attribute value in jsp:useBean, the default scope value is page. Other values are request, session, and application.

Q #23) Can we handle a runtime exception in the JSP page?

Answer: Yes, the runtime exceptions occur due to an error during JSP page execution, can be handled by catch and handle exception in Java scriplet, using standard exception handling code of Java.

Q #24) What is the use of the tag library in JSP?

Answer: Standard tag library in JSP are useful to overcome shortcomings of custom tags, there are three main tag libraries often used in JSP viz. core, SQL, and XML. They are mainly used for designing iteration and conditional tasks, manipulating XML documents, performing SQL operations on databases, and internationalization.

Q #25) What is the use of the JSP Declaration?

Answer: Variables, methods, and fields are declared in the JSP page using declaration tags. In JSP declaration, instance variables and methods are composed outside _jspService() method.

JSP declaration tags syntax is as below:

<%! declaring variable, method %>

whereas, Scriplet tags have syntax as below:

<%= "Hello Sir" %>

Q #26) What are the steps involved in reading data from a form using JSP?

Answer: The steps are as follows:

  1. Web pages send input data using form tags with web elements such as text field, checkbox for selection of multiple values, radio buttons for selecting one of the options, and submit button, in Java Server Pages (JSP).
  2. Client-side validation with JavaScript will make sure the user is alerted with messages in case invalid values are entered in input fields and are prevented when the submit button is clicked.
  3. The submit button in the form has an attribute POST or GET methods to send user input as a request using Hypertext Transfer Protocol (HTTP), using the browser.
  4. POST method is used when sensitive information such as credit card numbers, login credentials are entered in input fields. The values with the POST method will not display on the browser URL address bar.
  5. GET method can be used for information that is not sensitive and the values with GET method will get displayed on the browser URL address bar.
  6. JSP page uses the following methods to handle input data:
  • getParameter(): method is used to get input value from form element such as textfield
<%
String loggedinuser = request.getParameter("user_name");
String passwd = request.getParameter("pass");
%>
  • getParameterValues() method is used when multiple values (array) from form element such as checkbox options
<form ACTION="second.jsp">
<input type="checkbox" name="basket" value="Banana">Banana<BR>
<input type="checkbox" name="basket" value="Egg">Egg<BR>
<input type="checkbox" name="basket" value="Bread">Bread<BR>
<input type="checkbox" name="basket" value="Milk">Milk<BR>
<input type="submit" value="Submit">
</form>
<%
String shoppingcart[] = request.getParameterValues("basket");
For (int i = 0; i < shoppingcart.length; i++) {
out.println("Your have purchased " + shoppingcart[i] + "\n" +"which is total of " 
+ i+ "items" );
} %>
  • getParameterNames() returns an enumeration of all the parameter names associated with the request.
Enumeration enum = request.getParameterNames();

Q #27) Explain the importance of Session Data in JSP?

Answer: Java Server Pages which is a servlet that maintains status information about web visitors requesting the URL website address during a particular interval of time, is known as session tracking. Information about visitor visiting a website is saved with

setAttribute(String name,Object value) method as below:

session.setAttribute("user", name);

This session data can be retrieved using getAttribute(String name) method as below:

String name= (String)session.getAttribute("user");

Q #28) What are Cookies, their types, and how each type differs from the other?

Answer: Cookies are text files that are created in the client machine and store details of web searches or sites explored using the browser, date, and time of visit, along with IP address. The presence of cookies helps websites identify clients that return to their sites.

Cookies are of various types such as Authentication, Tracking, and Session cookies.

  • Session cookies are short-lived until the user explores a particular website, once he leaves the site, session cookies are deleted by browsers.
  • Tracking cookies as the name suggests keeps a record of how often a particular website has been visited.
  • Authentication cookies validate a genuineness of a valid user that revisits the website.

Q #29) List and describe action tags used in JSP.

Answer: JSP action tags are used to perform tasks such as the use of JavaBean, and controlling flow between web pages. The following are some of the action tags listed with details.

Action TagUse of action tags in JSP page
jsp:forwardrequest and response are forwarded to another resource with forward action tag, its syntax is like < jsp:forward page="relative url"/>, where relative url is either a page on server like /examples/index.html
jsp:includeWith this action tag another resource is included, the syntax is < jsp:include page="/aboutus/about-us.page?" />
jsp:useBeanThis action tag creates and locates bean object, its syntax is like
< jsp:useBean id=”name” class=”methodtype.class” />
jsp:setPropertyHelps to set value of property of a bean, its syntax looks like < jsp:setProperty name="bean" property="login" value="admin" />
jsp:getPropertyThis action tag prints the value of bean property with syntax like < jsp:getProperty name="beanobject" property="nameOfproperty" />
jsp:pluginWith plugin action tag another component such as applet can be embedded in JSP page, with syntax such as < jsp:plugin type = "applet" code="Appletname.class">< /jsp:plugin>
jsp:paramAction tag param sets the value of parameter in forward as well as include action tags with syntax like
< jsp:params>
< jsp:param name="shape" value="circle"/ >
< /jsp:params>

jsp:fallbackfallback action tag is used along with jsp:plugin tag to print a message to verify if plugin tag is working, its syntax looks like
< jsp:fallback>
< p>Class not found!< /p>
< /jsp:fallback>

Q #30) Why do you use JSP?

Answer: JSPs are used in order to develop dynamic web content, where input from visitor will be considered as a request, and model view controller as a web framework where the presentation layer is Java Server Pages (JSP) – Java code inside HTML/CSS/JavaScript code, business logic written in the middle layer, Controller will have Java classes, and Model has backend DAO(i.e. Hibernate) to access the database.

Conclusion

Java server pages are used for the client-server framework and help create dynamic web content by handling user input data requests and returning responses using HTTP. JSP page uses implicit objects, directives, custom tags, and scriplets for handling user data using various methods such as getParameter(String name), getParameterValues() to fetch multiple values from the form.

There are action tags used in the JSP page to perform various tasks.

All the best for the interview!!