Advertise with Us!
We have a variety of advertising options which would give your courses an instant visibility to a very large set of developers, designers and data scientists.View Plans
Top 50 JSP Interview Questions & Answers
What is JSP?
JSP stands for JavaServer Pages. JSP is Java server-side technology to create dynamic web pages. JSP is an extension of Servlet technology to help developers create dynamic pages with HTML like syntax.
The user creates user views in servlets as well, but the code becomes ugly and error-prone. Moreover, as most of the elements on a web page are static, therefore JSP page is suitable for web pages. Business logic in JSP pages should be avoided and must be used for view purposes only.
JSP Interview Questions
Let us now see popular JSP Interview Questions.
Question: What are the benefits of JSP?
Answer: Using JSP scripting elements for writing Java code in JSP pages should be avoided, and JSTL tags, JSP action elements, or custom tags should be used instead to achieve the same functionalities.
Another benefit of JSP is that most of the containers support the hot deployment of JSP pages. Make the changes in the JSP page and replace the old page with the updated JSP page in the deployment directory, and the container loads the new JSP page. We are not required to compile our project code or restart server, unlike when making changes in servlet code, where we need to build the complete project again and deploy. Although most of the containers provide hot deployment support for applications still, it’s more work than JSP pages.
Question: Explain the lifecycle phases of JSP
A typical JSP page code looks like HTML and doesn’t look anything like java classes. The JSP container takes care of translating the JSP pages and create the servlet class that is used in web applications. Following are the phases of a JSP lifecycle:
- Translation: JSP code is checked and parsed to generate the servlet source code. For example, in Tomcat, made servlet class files are found at directory named TOMCAT/work/Catalina/localhost/WEBAPP/org/apache/JSP. If home.jsp is the JSP page name, then usually the generated servlet class name is home_jsp, and the home_jsp.java is the file name.
- Compilation: In this phase, the JSP container compiles the JSP class source code, and a class file is produced.
- ClassLoading: In this phase, the container loads the class into memory.
- Instantiation: The no-args constructor of the generated class is invoked by the container to load it into memory and instantiate it.
- Initialization: The init method of the JSP class object is invoked by the container, and the servlet config is initialized with init params configured in the deployment descriptor. JSP is ready to handle client requests after this phase. Usually, translation to the initialization of JSP happens when the first request for JSP comes. Still, we can configure it to be loaded and initialized at the time of deployment, like servlets using a load-on-startup element.
- Request Processing: This is the most extended lifecycle of the JSP page when the client requests are processed. The processing is multi-threaded, similar to servlets, and a new thread is spawned for every application. Servlet requests and ServletResponse objects are created, and the JSP service method is invoked.
- Destroy: It is the last phase of the JSP lifecycle, where the JSP class is unloaded from memory. Usually, it happens when the application is undeployed, or the server is shut down.
Question: Discuss JSP lifecycle
Answer: JSP lifecycle consists of the following methods:
- jspInit(): It is a method that is declared in JspPage, and it’s implemented by JSP container implementations. The method is called once in the JSP lifecycle to initialize it with config params configured in the deployment descriptor. We can override this method using the JSP declaration scripting element to initialize any resources that we want to use in the JSP page.
- _jspService(): It is the JSP method that gets invoked by JSP container for each client request bypassing request and response object. Notice that the method name starts with an underscore to distinguish it from other lifecycle methods as this method cannot be overridden. All the JSP code goes inside the method and is replaced by default. We should not try to replace it using the JSP declaration scripting element. The method is defined in the HttpJspPage interface.
- jspDestroy(): This method is called by the container when JSP is unloaded from memory, such as shutting down applications or box. The method is called only once in the JSP lifecycle, and this method is overridden to release resources created in JSP init method.
Question: Is it possible to override the JSP lifecycle methods? If yes, which of the methods can be overridden?
Answer: Yes, we can override JSP lifecycle methods.Methods such as jspInit() and jspDestroy() can be overridden by using JSP declaration scripting element. We override jspInit() methods to create common resources that we would like to use in the JSP service method and override the jspDestroy() method to release the common resources.
Question: Mention the literals used in JSP
Answer: JSP uses the following literals;
Question: List three important tags used in the development of JSP Bean
Answer: The JSP Bean development uses the following three tags as follows:
Question: What are the different types of comments in JSP?
Answer: There are two types of comments provided by JSP pages that we can use:
- HTML Comments: We can use HTML comments like <!-- HTML Comment --> since JSP pages are like HTML. These comments are sent to the client as well and can be seen in the HTML source. So we must avoid debugging comments or code level comments using HTML comments.
- JSP Comments: Scriptlets like <%-- JSP Comment --%> are used for writing JSP comments. These comments are not sent to the client an are present in the generated servlet source code. We should use JSP comments for any code level or debugging information comments.
Question: Describe the scripting elements in JSP
Expression, Scriptlets, and Declaration are scripting elements in the JSP page using which add java code in the JSP pages.
Any code written inside the scriptlet tags goes into the _jspService() method. A scriptlet tag begins with <% and ends with %>.For example;
Date dt = new Date( );
System.out.println("Current Date=" +dt);
There is a shortcut to printing dynamic data in the JSP page using the out.print( ) method through JSP Expressions. JSP Expression begins with <%= and ends with %>.
<% out.print("John"); %> can be written using JSP Expression as <%= "John" %>
Make a note that anything within <%= %> is sent as a parameter to the out.print() method. Also, note that scriptlets can contain multiple java statements and always ends with a semicolon (;), but the expression doesn’t end with a semicolon.
Declaration of member variables and methods of the servlet class are made using JSP Declarations. JSP Declarations begins and ends with " <%! " , " %>" respectively.
For example, we create an int variable in JSP at the class level as <%! public static int count=0; %>.
Question: Differentiate between hiding comment and output comment.
Answer: The JSP comment is called hide comment, whereas the HTML comment is called the output comment. The JSP comment will not be shown in the case if a user views the source of the page, whereas HTML comments will be displayed.
Question: Why the use of scripting elements in JSP discouraged?
Answer: JSP pages are used for view purposes, and all the business logic should be in the servlet or model classes. We should pass parameters to the JSP page through attributes and then use them to create the HTML response in the JSP page.
Most of the JSP page contains HTML code and to help web designers to understand JSP page and develop them quickly, JSP technology provides action elements, JSP Standard Tag Library, JSP EL, and custom tags that we use rather than scripting elements to bridge the gap between JSP HTML and JSP java part.
Question: What are the five types of JSTL tags?
Answer: They are categorized into five types based on the JSTL functions:
- Core Tags: Provides support for iteration, conditional logic, catch the exception, URL, forward or redirect response, and more.
- Formatting and Localization Tags: Provided for the formatting of Dates, Numbers, and i18n support through resource bundles and locales.
- SQL Tags: Provide support for interaction with relational databases such as Oracle, MySql, and more.
- XML Tags: Used to work with XML documents such as parsing XML, transforming XML data and XPath expression evaluation.
- JSTL Functions Tags: JSTL tags provide several functions that we can use to perform the standard operation; most of them are for String manipulation such as String Concatenation, Split String, and more.
Question: What is JSP Custom Tag, and what are the components of a JSP custom tag?
Answer: Action Tags, JSP EL, and JSTL tags are not enough sometimes, and it might tempt us to write code in Java to perform some operations on the JSP page. Luckily, JSP is extendable, and we can create custom tags to deliver certain services.
We can create JSP Custom Tags with the following components:
- JSP Custom Tag Handler
- Creating Tag Library Descriptor (TLD) File
- Deployment Descriptor Configuration for TLD
We can add a custom tag library in the JSP page using a taglib directive and then use it.
Question: What are JSP implicit objects?
Answer: Objects created by the web container while translating the JSP page to Servlet source to help developers are JSP implicit objects. We use these objects directly in scriptlets that go in the service method. However, they can't be used in JSP Declaration because that code will go at the class level.
We have nine implicit objects that we can directly use in the JSP page. Seven of them are declared as a local variable at the start of the _jspService() method, whereas two of them are part of the _jspService() method argument that we can use.
Question: We can use JSP implicit objects in a method defined in the JSP Declaration? True or False? Justify
Answer: False! Because these objects are local to service method, as well these JSP implicit Objects are added by JSP Container. Also it is translating JSP page to servlet source code. JSP Declarations code went outside the service method, and It is used to create class level variables and methods. Hence can’t use JSP implicit objects.
Question: How to include static files in a JSP?
Answer: Static pages can be included in a JSP using the include directive. The inclusion is performed once this way in the translation phase. A relative URL must be supplied for the file attribute. Though static resources may be included, it is not preferred as each request requires inclusion.
Question: Explain Client-Side and Server-Side Validation.
Server-side validation is trusted to execute without fail on all input. The client is supposed to wait for a response from the server before displaying any success or error message to the user since the server can’t execute its validation until it’s received an HTTP request. In the case of validation failure, an extra network trip is needed to resend the form to fill out the form with the correct data by the client.
Question: Explain JSP declaration
Answer: Declaration fields and methods are done using the JSP declaration tag. The code is wrapped inside <%!%> tag and is placed outside of the service( ) method of the auto-generated servlet. Therefore, it does not get memory at each request.
<%! field or method %>
<%! int val=50; %>
<%= "Value of the variable is:"+val %>
Question: Distinguish between JSP Scriptlet and JSP Declaration.
|JSP Scriptlet||JSP Declaration|
|It can only declare variables and not methods.||It can declare both methods and variables.|
|It is placed inside _jspService( ) method.||It is placed outside _jspService( ) method.|
Question: What are the advantages of JSP over ASP?
- It is powerful and easier to use as the dynamic part of the code is written in Java, not Visual Basic or the Microsoft-specific language.
- It is portable to Non-Microsoft Web servers and other operating systems.
Question: Define the JSP custom tag and its components.
Answer: Custom tags are user-defined tags; we can define our tags with our functionality and use those tags inside the JSP page.
It offers the following advantages:
- It eliminates the need for the scriptlet tag.
- Separation of business logic from the JSP page
- Reusability of the JSP page.
It consists of the following components:
- Custom tag handler class.
- Create a TLD (Tag Library Descriptor) file.
- Deployment Descriptor Configuration for TLD
We can add a custom tag library in the JSP page using a taglib directive and then use it.
Question: How to configure init params for JSP?
Answer: We can configure init params for JSP similar to the servlet in web.xml file; Also it is necessary to configure JSP init params with servlet and servlet-mapping element. The only thing that differs from the servlet is a jsp-file element, where we need to provide the JSP page location.
Question: Distinguish between including Directive and include Action in JSP
|Include Directive||Include Action|
|It is processed at translation time.||It is processed at run time.|
|It uses a relative or absolute path||It uses a relative path.|
|No other parameters can be passed.||Other parameters can be passed.|
|It includes the contents of resources only and will not process the dynamic resource.||It processes the dynamic resource, and the result will be added to calling JSP|
|Passing any request or response object to calling jsp to included file or JSP or vice versa is not allowed.||Passing any request or response object to calling jsp to included file or JSP or vice versa is allowed.|
Question: What are JSP Action Elements or Action Tags? Explain
Answer: Tags provide useful functionalities like including resources, working with Java Bean, forwarding the request, and to generate dynamic XML elements. Action elements start with jsp: and can be used in JSP pages directly without the need to import any tag libraries or any other configuration changes. The JSP tags are:
|jsp:forward||forwards the response and request to another resource.|
|jsp:include||includes another resource|
|Jsp: use of bean||Locates or creates bean objects|
|jsp:setProperty||value of the property is set in the bean object|
|jsp:getProperty||prints the value of the property of the bean|
|jsp:plugin||embeds another component like an applet|
|jsp:param||sets the parameter value. It is used in forward and includes mostly.|
|jsp:fallback||can be used to print the message if the plugin is working. It is used in jsp: plugin.|
Question: What is JSP Expression Language(EL)?
Answer: JSP EL simplifies the accessibility of data stored in Java bean components and other objects like request, application, and session.
Question: How to use JSP EL to get the HTTP method name?
Answer: pageContext JSP EL implicit object is used to get the request object reference, and the dot operator is used to get the HTTP method name in the JSP page.
Below is the code snippet for the same:
Question: Can a JSP extend another java class? If yes, how?
Answer: Yes, JSP can extend another JSP using this
<%@ include page extends="classname" %>
it’s a correct because when JSP is converted to servlet its implements javax.servlet.jsp.HttpJspPage interface, so jsp page extends another java class.
Question: How does JSP communicate with Java files?
Answer: The import tag
<%@ page import="market.stock.*” %>
like this, we import all the java files to jsp and use them as a regular class. The other way is servlet can send the instance of the java class to jsp, and that object can be retrieved from the request object and use it on the page.
Question: Which directive is used in the JSP custom tag?
Answer: JSP taglib directive.
Question: Name the three tags used in JSP development.
Question: What is the syntax for JSP comments?
<%-- Comment --%>
Question: Is JSP technology extensible? How?
Answer: Yes, JSP technology can be extensible through the development of tags or custom actions that are encapsulated in tag libraries.
Question: How can a thread-safe JSP page be implemented?
Answer: By having JSPs implement the SingleThreadModel interface, we can make them thread-safe. This can be done by adding the directive <%@ page isThreadSafe="false" %> within the JSP page.
Question: Define JSP expressions
Answer: Scripting language expression contained inside a JSP expression element is first evaluated, then converted to a String, and then inserted where the expression appears in the JSP file.
The expression element may contain any expression that is valid according to the Java Language Specification, but semicolon cannot be used to end an expression.
<% expression %>
Question: Define the JSP directive?
Answer: The overall structure of the servlet class is affected by a JSP directive. It has the following form:
<%@ directive attribute = "value" %>
Question: State the types of directive tags?
|<% @page … %>||Defines page dependent attributes.|
|<% @include … %>||File is included during the translation phase.|
|<% @taglib ... %>||Declares a tag library, containing custom actions, used in the page.|
Question: Define JSP literals
Answer: Literals are defined as the values, such as a text string or a number, that are written as part of the code.
JSP literals are:
|Boolean||True or false|
|String||with single and double quotes; " is escaped as \," ' is escaped as \,' and \ is escaped as \\.|
|Integer||As in Java|
|Floating Point||As in Java|
Question: How are JSP runtime exceptions handled?
Answer: Exception is defined as an abnormality thrown at runtime, and the process handling the runtime errors is called exception handling.
In JSP the exceptions are handled in two ways:
- By errorPage and isErrorPage attributes of page directive
- By <error-page> element in web.xml file
Question: What is the page directive?
Answer: The page directive provides instructions to the container that pertain to the current JSP page. Page directives can be coded anywhere on the JSP page.
Question: Why does the _jspService() method starts with an '_' while other life cycle methods do not?
Answer: jspInit() jspDestroy() and _jspService() are main JSP life cycle method, by default whatever content is written in JSP page goes inside the _jspService() method by the container if again tries to override this method JSP compiler will give an error but we can override other two life cycle method as implementing this two in JSP so making this difference container use _ in jspService() method and shows that the method cannot be overridden.
Question: How is JSP used in the MVC model?
Answer: JSP is used for presentation in the Model View Controller pattern (MVC ); it means it plays the role of the view. The controller calls the model and the business classes, which in turn get the data, and this data is then presented to the JSP for rendering on to the client.
Question: Can the jspInit(), _jspService() and jspDestroy() methods be overridden?
Answer: We cannot override _jspService() method but jspinit() and jspDestroy() methods can be overriden.
Question: When to use application scope?
Answer: It is used when we want to make data available to the entire application.
Question: Differentiate between JavaBeans and taglib directives
Answer: JavaBeans and taglib were introduced for reusability. The following are the major differences between them −
- JavaBeans are good for storing information and state, whereas Taglibs are for generating presentation elements.
- Use custom tags to implement actions and JavaBeans to present information.
Question: How is information is passed from JSP to included JSP?
Question: Define the auto-refresh feature
Answer: Imagine a webpage displaying live game score or stock market status or currency exchange ratio. The webpage needs to be refreshed regularly using the refresh or reload button with your browser for all such types of pages.
JSP makes this job easy by providing a mechanism where a webpage can be made in such a way that it would refresh automatically after a given interval.
Question: How is the auto-refresh implemented in JSP?
Answer: The simplest way of refreshing a Web Page is using the method setIntHeader() of the response object. Following is the signature of this method −
public void setIntHeader(String header, int header value)
This method sends back header "Refresh" to the browser along with an integer value, which indicates the time interval in seconds.
Question: Define JSTL SQL tags?
Answer: The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such as Oracle, MySQL, or Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in your JSP −
<%@ taglib prefix = "sql" uri = "http://java.sun.com/jsp/jstl/sql" %>
Question: What type of errors can a JSP code encounter?
- Checked exceptions: An exception that is a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions are difficult to ignore.
- Runtime exceptions: An exception that occurs could probably have been avoided by the programmer. Runtime exceptions are ignored at the time of compilation.
- Errors: These are not considered as exceptions, but the problems that arise beyond the control of the user or the programmer. Errors are ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
Question: How to disable scripting?
Answer: We can disable scripting by setting the scripting-invalid element of the deployment descriptor to true. It is a subelement of the jsp-property-group. Its valid values are true and false. The syntax for disabling scripting is:
It can be stressful to prepare for an interview and so here we present you with the most popular JSP Interview questions for you to crack your JSP interview. Do you have any more questions to share? Or have any tips to crack this interview?
JSP, Servlets, and JDBC for Beginners: Build a Database App is some of the popular Udemy courses when preparing for a JSP interview.
Seeking a JSP interview questions book? Refer to this to sharpen your JSP Skills: Top 1000 Java Interview Questions: Includes Spring, Hibernate, Microservices, GIT, Maven, JSP, AWS, Cloud Computing: (latest 2018 edition).
Let us know in the comments below!!
People are also reading:
- PHP Interview Questions
- Python Interview Questions
- Technical Interview Questions & Answers
- C Interview Questions & Answers
- Java Interview Questions
- AWS Interview Questions
- Difference between coding vs programming
- Which Programming Languages is best for getting Jobs?
- How to become a Backend Developer?