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).
Table of Contents:
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.
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:
Servlet | Java Server Page |
---|---|
Servlet is Java code, is hard to code than JSP | Java Server Page is tags in HTML page, easy as it is Java in html page. |
Servlet plays as controller role in MVC approach | JSP plays as view in MVC approach |
In Servlet, service() method can be overridden | In JSP, service() method cannot be overridden. |
Session management is not enabled by default | Session 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.
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 system | JSP 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:
PHP | JSP |
---|---|
PHP stands for Hypertext Preprocessor, is an open source server side scripting language with huge community and library | JSP 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 tags | JSP 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 cheap | It 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:
Object | Type | Use in JSP |
---|---|---|
Out | JspWriter | Out is used for writing any data to the buffer, JspWriter object is used in JSP page |
Request | HttpServletRequest | Request 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 |
Response | HttpServletResponse | Response is used to add or update response as redirect response to another resource or send an error in case redirect does not work. |
Config | ServletConfig | Config object like ServletConfig used in order to get initialization parameters from web.xml |
Application | ServletContext | ServletContext is an application instance works as config object as well get, set or remove attribute from application scope. |
Session | HttpSession | Session object is used for get, set or remove attribute or get session information. |
PageContext | PageContext | PageContext object is used to get, set or remove attribute from page, request, session and application objects. |
Page | Object | Page are assigned to reference of auto generated servlet class. |
Exception | Throwable | Exception 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 Directive | Include 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 validation | Server 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 VBScript | Server 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 Tags | JavaBeans |
---|---|
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 Name | Description |
---|---|
buffer | It indicates buffering model for output stream |
autoFlush | Servlet output buffer behavior is controlled with this attribute |
contentType | Character encoding scheme related attribute |
errorPage | Uniform Resource Locator for another JSP that reports Java unchecked runtime exceptions. |
isErrorPage | Indicates URL specified by JSP page’s errorPage attribute defined above. |
extends | Superclass generated Servlet must extend is specified with this attribute |
import | Similar to Java classes, import attribute is used to list packages or classes for use in JSP page. |
info | This attribute is defined as a string accessed by Servlet’s getServletInfo() method, |
isThreadSafe | This attribute defines threading model for Servlet |
language | Declares programming language used in JSP pages. |
session | Declares JSP page participation in HTTP sessions. |
isELIgnored | Attribute decides whether to EL expression within JSP will be ignored or not. |
isScriptingEnabled | Whether 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:
- 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).
- 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.
- 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.
- 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.
- 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.
- 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 Tag | Use of action tags in JSP page |
---|---|
jsp:forward | request 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:include | With this action tag another resource is included, the syntax is < jsp:include page="/aboutus/about-us.page?" /> |
jsp:useBean | This action tag creates and locates bean object, its syntax is like < jsp:useBean id=”name” class=”methodtype.class” /> |
jsp:setProperty | Helps to set value of property of a bean, its syntax looks like < jsp:setProperty name="bean" property="login" value="admin" /> |
jsp:getProperty | This action tag prints the value of bean property with syntax like < jsp:getProperty name="beanobject" property="nameOfproperty" /> |
jsp:plugin | With 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:param | Action 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:fallback | fallback 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!!