JSP Interview Questions and Answers

JSP Interview Questions and Answers

In this article, I am going to discuss the most frequently asked top 100 JSP Interview Questions and Answers. Once you go through these JSP Interview Questions and Answers, I am sure you will crack the JSP Interview easily.

What is JSP?

Java Server Pages (JSP) technology is the Java platform technology for delivering dynamic content to web clients in a portable, secure, and well-defined way. The Java Server Pages specification extends the Java Servlet API to supply web application developers with a strong framework for creating dynamic web pages on the server using HTML, and XML templates, and Java code, which is secure, fast, and independent of server platforms. JSP has been built on top of the Servlet API and utilizes Servlet semantics. JSP has become the well-liked request handler and response mechanism. Although JSP technology goes to be a strong successor to basic Servlets, they need an evolutionary relationship and may be utilized in a cooperative and complementary manner.

Explain the benefits of JSP?
  1. JSP pages are faster because they are pre-compiled.
  2. It is flexibles as it’s part of the Sun’s J2EE and can be used with other types of Java technologies, such as Servlet.
  3. It is a ‘fly by night’ technology as multiple vendors support it because of its specifications.
  4. It is easy to develop because HTML can be easily maintained with JSP. Relatively minimal programming skills required.
  5. JSP page code is not visible to the client, only generated HTML is visible.
  6. It is easy to read, write, and maintain JSP pages.
  7. It is easy to extend the JSP language by using pluggable, reusable tag libraries available.
What is a JSP page?

A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content.

Is JSP technology extensible?

YES, JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

Can we implement an interface in JSP?

Yes, we can implement an interface in JSP by importing a class in JSP.

What are the advantages of JSP over Servlet?

This is one of the frequently asked JSP Interview Questions and Answers. JSP technology was designed to simplify the process of creating pages. It simplifies the process by separating web presentations from web content. JSP is a collection of HTML tags and JSP tags and Java code. Every JSP page is saved with ext.jsp (ext-> extension). This JSP can be placed in the root folder or WEB-INF. The JSP placed in the root folder is a public resource and this resource can access by the client directly. The JSP placed inside WEB-INF is a private resource, which can’t access directly by the client. Client access this resource using public URL defined inside web.xml.

Servlets are powerful and sometimes they’re a touch cumbersome when it involves generating complex HTML. Most servlets contain a touch code that handles application logic and tons of more code that handles output formatting. This can make it difficult to separate and reuse portions of the code when a special output format is required. For these reasons, web application developers turn towards JSP as their preferred servlet environment.

What is the difference between Servlet and JSP?
  1. If we perform any modifications on the existed Servlets then we have to perform recompiling and reloading on to the server explicitly whereas if we perform any modifications on the existed JSP then it is not required to perform recompilation and reloading because JSP pages are auto compiled and autoloaded.
  2. In JSP business logic is isolated from presentation logic by using JavaBeans, whereas in Servlet we have to execute everything like business logic and presentation logic in one servlet file.
  3. Session Management is automatically enabled in JSP, whereas in Servlet, by default session management is disabled, the user needs to enable it explicitly.
  4. From a performance perspective, JSP is slower than Servlet because the initial step is the translation of JSP to java code in the JSP lifecycle and then compile.
  5. In JSP, packages can be imported anywhere top, middle and bottom, whereas, in Servlet, every package needs to be imported on top of the Servlet.
  6. JSP is used for displaying output data whereas Servlet plays a controller role in the MVC pattern.
Explain the difference between ASP and JSP?
  1. JSP stands for Java Server Pages is a technology introduced by Sun microsystems whereas ASP stands for Active Server Pages is a technology introduced by Microsoft.
  2. ASP pages can connect to MYSQL and MS Access databases and also can connect to other databases with the help of ADO whereas JSP can connect to any databases loading the appropriate driver when needed.
  3. JSP is a technology that helps the developers to implement and develop dynamic web pages, whereas ASP is Microsoft’s server-side script engine for dynamically generated web pages.
  4. With respect to performance perspective, JSP code runs faster than ASP.
  5. JSP is mainly used by Apache Tomcat Web Server and mainly implemented on Linux based web server and also runs on JBoss and IBM application server, whereas ASP is mainly based on Microsoft IIS server and is implemented on windows-based systems.
  6. JSP is free of cost whereas ASP is not free and requires a proper license for usage.
  7. JSP mainly works with Java Security Model whereas ASP is mainly based on the Windows NT Security Architecture Model.
Can we stop JSP execution while in the midst of processing a request?

Yes, we can stop execution in the midst of processing a request by the Preemptive termination of request processing. It is a good way to maximize the throughput of a high-volume JSP engine.

Why are JSP pages are preferred for creating a web-based client program?

Because no plug-ins or security policy files are needed on the client systems (applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their job.

How to protect JSP from direct access?

We can protect direct access by descriptor security to the JSP or page flow using a URL. We cannot use it when a portal renders a portlet.

What is JSP API?

The JSP API consists of two packages:

  1. javax.servlet.jsp
  2. javax.servlet.jsp.tagext

Package javax.servlet.jsp: The javax.servlet.jsp package contains a number of classes and interfaces. The classes and interfaces in javax.servlet.jsp package describes and defines the contracts between the runtime environment provided for an instance of such a class by a conforming JSP container and a JSP page implementation class.

Package javax.servlet.jsp.tagext: It provides a portable mechanism for the description of tag libraries. It contains a tag library descriptor and a number of Tag Files or Tag Handler classes defining request-time behavior. It also contains additional classes and resources used at runtime and possibly some additional classes to provide extra translation information

What are the lifecycle phases of JSP?

This is one of the frequently asked JSP Interview Questions and Answers. JSP Life Cycle is defined as the translation of the JSP Page into the servlet. Because JSP Page always needs to be converted into servlet page first in to process the service requests. JSP page life cycle contains the following phases:

JSP Interview Questions and Answers

Please read our JSP Life Cycle article for more detail.

Explain lifecycle methods in JSP?

This is one of the frequently asked JSP Interview Questions and Answers. The lifecycle of JSP is controlled by three methods which are automatically called, when a JSP is requested and when the JSP terminates normally. These are: jspInit(), _jspService() and jspDestroy()

  1. jspInit() method is similar to the init() method in a Java Servlet and an applet. It is called first when the JSP is requested and is employed to initialize objects and variables that are used throughout the lifetime of the JSP.
  2. _jspService() method is automatically called and retrieves a connection to HTTP. It will call the doGet or doPost() method of servlet created.
  3. jspDestroy() method is similar to the destroy() method in Servlet. The destroy() method is automatically called when the JSP terminates normally. It isn’t called by JSP when it terminates. It is used for cleanup where resources used during the execution of the JSP are released.
What JSP lifecycle methods can I override?

jspInit() and jspDestroy() methods can be overridden and we cannot override _jspService() method.

How can I override the jspInit () method within a JSP page?

We can override the jspInit() method to perform the initialization task i.e. allocating resources like database connections, network connections, etc. It can be overridden by a page author to initialize the resources.

How do we prevent the output of my JSP or Servlet pages from being cached by the browser?

We need to set appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Execute the following codes before the JSP pages:

Response.setHeader (“Cache-Control”,”no-store”); //HTTP 1.1
Response.setHeader (“Pragma\”,”no-cache”); //HTTP 1.0

What is the difference b/w variable declared inside a declaration part and a variable declared in the scriptlet part?

Variable declared inside declaration part is treated as a global variable, that means after conversion JSP file into servlet that variable will be in outside of service method or it will be declared as an instance variable. And the scope is available to complete JSP and to complete in the converted servlet class, where if u declare a variable inside a scriptlet that variable will be declared inside a service method and the scope is within the service method.

Is there a way to execute a JSP from the command line or from my own application?

No, we cannot execute JSP through the command line. JSP needs a servlet engine to convert it into servlet code and run.

Explain about translation and execution of JSP?

This is one of the frequently asked JSP Interview Questions and Answers. First, the container loads the .jsp file from memory. Then container verifies the syntax of JSP tags placed in the .jsp file. Using the JSP page compiler JSP program will be converted into an equivalent servlet class. The java compiler (javac) compiles the JES class source file. Then container loads JES class and creates the object. Container then calls jspInit() method through init(ServletConfig) method to initialize ServletConfig object with JES class object. Then it creates one set of requests, response object from the current request. The container then calls the _jspService(_,_) method of JES through service(_,_) to process the request. The output generated by the _jspService(_,_) method goes to the browser as a response. Once the response is delivered to the request, the response object will be destroyed. If there is no further request to JSP or if the web application stopped/reloaded the container performs servlet de-instantiation. When this is about to happen container calls jspDestroy() through the destroy() method. JVM then unloads the loaded JES class. At last container unloads the loaded .jsp file.

Why is _jspService() method starting with an ‘_’ while other lifecycle methods do not?

_jspService() method is starting with an ‘_’ because it is written by the container and cannot be overridden by the end-user.

How do I use a scriptlet to initialize a newly instantiated bean?

By using jsp:useBean as it contains the body. As the body is specified its contents will be automatically invoked when the specified bean is instantiated. Basically, the body contains scriptlets or jsp:setProperty tags to initialize the newly instantiated bean.

How to pre-compile JSP?

To select precompilation, right-click the EAR or WAR file you wish to export and select Export > EAR file or Export > WAR file. In the Export dialog, select the checkbox Pre-compile JSP.

Note: The pre-compile JSP option is available only to projects targeted to WebLogic Server 9.2 and 10.0 runtimes.

Explain the benefits of precompiling a JSP?
  1. Avoids initialization on the first page.
  2. Avoids execution of _jspService method.
  3. Provides better performance on the first request.
Explain JSP Scripting elements and their types?

This is one of the frequently asked JSP Interview Questions and Answers. In web applications, JSP Scripting Elements are often wont to provide code in JSP pages. All the JSP Scripting Elements are going to be resolved at the time of request processing. The majority of Scripting Elements will give a direct effect to response generation. JSP scripting elements enable you to insert java code directly into the servlet that will be generated from the current JSP page. There are three types of Scripting Elements:

  1. Declarations: Declaration of the form that is inserted into the body of the servlet class, outside of any existing methods.
  2. Scriptlets: Scriptlets of the form that are inserted into the servlets service method.
  3. Expressions: Expressions of the form that are evaluated and inserted into out.
What is a Scriptlet?

This scripting element is often wont to provide a block of java code. It can contain any number of language statements, variable or method declarations, or expressions that are valid within the page scripting language. Within a scriptlet, you can do the following:

  1. On the JSP page declare variables or methods to use later.
  2. Write valid expressions in the page scripting language.
  3. Use any of the implicit objects or any object declared with the element.
  4. On the JSP page, write any other statement valid in the scripting language used.
  5. All text, HTML tags, or JSP elements you write must be outside the scriptlet.
What are JSP declarations?

It provides all the java declarations like variable declarations, method definitions. Classes declarations and so on. A declaration can consist of either method declarations or variables, static constants are a good example of what to put in a declaration. The JSP you write turns into a category definition. All the scriptlets you write are placed inside one method of this class. You can also add variable and method declarations to the present class. You can then use these variables and methods from your scriptlets and expressions. We can use declarations to declare one or more variables and methods at the category level of the compiled servlet.

What is an Expression?

An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like

<% = some expression %>
<% = (new java.util.Data()).toLocaleString() %>
You cannot use a semicolon to end an expression

What’s a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or synchronization?

As SinleThreadModel works well for low volume sites it does not scale well. If you want to increase your number of users in the future it is better to use the synchronization approach. As synchronization minimize the amount of code so that you can take maximum advantage of multithreading.

Difference between forward and sendRedirect?

This is one of the frequently asked JSP Interview Questions and Answers. In forward(), redirect happens at the server end and not visible to the client, wherever in sendRedirect(), redirection happens at the client end and it’s visible to the client.

What are the different scope values for the < jsp:usebean >?

The different scope values for <jsp:useBean> are

  1. Page
  2. Request
  3. Session
  4. Application
How can I declare methods within my JSP page?

When you write a declaration during a JSP page, remember these rules:

  1. Must end the declaration with a semicolon.
  2. <% int i=0;%>
  3. We can use variables or methods that are declared in packages imported by the page directive, without declaring them in a declaration element.
  4. We can declare any number of variables or methods within one declaration element, as long as you end each declaration with a semicolon. The declaration must be valid in the Java programming language.

Syntax: <%!

What is the difference between a variable declared inside a declaration and a variable declared in a scriptlet?

If a variable is declared inside the declaration part then it is treated as a global variable which means that after conversion of JSP file into Servlet file that variable will be declared as an instance variable. Whereas, if we will declare a variable inside a scriptlet then that variable will be declared inside a service method and the scope is within the service method.

What are the three kinds of Comments in JSP?

In JSP pages, we are able to use the following three types of comments:

  1. XML-Based Comments: It is used to comment on HTML code or template text of JSP programs. It will be recognized by an HTML interpreter.
  2. JSP-Based Comments: It is used to comment on JSP tags. It will be recognized by the JSP page compiler. It is a comment that documents the JSP page but is not sent to the client.
  3. Java-Based Comments inside Scripting Elements: It will be recognized by javac. It is visible in the JES source. But is not visible in JES bytecode, HTML that goes to the browser as well as output.
What is an output comment?

It is used to comment on HTML code or template text of JSP programs. It will be recognized by an HTML interpreter. It is visible in JES source code, JES byte code as well as HTML that goes to the browser. It is not visible in the output. It is a comment that is sent to the client in the viewable page source. The JSP engine handles an output comment as uninterpreted HTML text, returning the comment within the HTML output sent to the client. You can see the comment by viewing the page source from your browser

Syntax: <! – – Comment – – >

What is Hidden Comment?

It is used to comment on JSP tags. It will be recognized by the JSP page compiler. It is a comment that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment and doesn’t process any code within hidden comment tags. A hidden comment isn’t sent to the client, either within the displayed JSP page or the HTML page source. The hidden comment is beneficial once you want to cover or comment out a part of your JSP page. It is not visible in JES source, JES bytecode, HTML that goes to the browser as well as output.

Syntax: <% – – Comment – – %>

How is scripting disabled?

You can disable scripting for a group of JSP pages in an application in one of two ways:

  1. Select the Ignore JavaScript check box in the JSP Property Group node of the NetBeans IDE web.xml editor.
  2. Set the scripting-invalid element of the application’s deployment descriptor to true. The scripting-invalid element is a child of the JSP-property-group element that defines properties for a set of JSP pages.
What are JSP Implicit Objects?

This is one of the frequently asked JSP Interview Questions and Answers. Implicit Objects are a set of Java objects which the JSP Container makes available to developers on each page. These objects can be accessed as built-in variables via scripting elements. It can also be accessed programmatically by JavaBeans and Servlets. These are created automatically for you within the service method. The JSP Implicit objects are as follows:

  1. Request
  2. Response
  3. pageContext
  4. session
  5. application
  6. out
  7. config
  8. page
  9. exception
How does JSP handles runtime exceptions?

Any runtime error encountered is handled using the following ways:

  1. Catch and handle exceptions in a Java scriptlet within the JSP page itself.
  2. Exceptions that do not catch in JSP will result in the forwarding of the request and an uncaught exception to an error page.
How can I implement a thread-safe JSP page? What are the advantages of using it?

This is one of the frequently asked JSP Interview Questions. You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe=”false” %> within your JSP page.

With this, instead of a single instance of the servlet loaded and initialized, the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets. If you do use this tag, then you should set isThreadsafe to true.

What is the difference between ServletContext and PageContext?

SrvletContext gives information about the container and represents an application whereas PageContext gives information about the Request and provides all the other implicit JSP objects.

Is there a way to reference the “this” variable within a JSP page?

Yes, there is a way to reference “this” variable by page implicit object. It is equivalent to “this” variable and returns a reference to the servlet generated by the JSP page.

How do you connect to the database from JSP?

This is one of the frequently asked JSP Interview Questions and Answers. A Connection to a database can be established from a jsp page by writing the code to establish a connection using a jsp scriptlets. The code below help you get started:

<%@ page import="java.sql.*"%>
<title>JDBC Connection example</title>
 <h1>JDBC Connection example</h1>

  try {
  String connectionURL = "jdbc:mysql://localhost:3306/JspDatabase";
  Connection connection = null;
  connection = DriverManager.getConnection(connectionURL, "root", "");
  if (!connection.isClosed())
   out.println("Successfully connected");
 } catch (Exception ex) {
  out.println("Unable to connect to database");


JSP Interview Questions and Answers

How can I enable session tracking for JSP pages if the browser has disabled cookies?

You can enable the session tracking for JSP pages using URL rewriting if the browser has disabled session tracking or if the browser does not support cookies. As URL rewriting includes the session ID within the link itself as a name or value pair.

What is autoFlush?

autoFlush is an attribute that specifies whether the buffered output should be flushed automatically when the buffer is filled or when an exception is occurred to indicate the buffer overflow.

Can a JSP page instantiate a serialized bean?

Yes, a JSP page can instantiate a serialized bean by using the useBean action which specifies the beanName attribute.

Can we use the constructor instead of init() to initialize the servlet?

This is one of the frequently asked JSP Interview Questions and Answers. Yes, we can use constructors in Servlet implementation but it should use the init() method because we cannot declare constructors on the interface in Java, and Servlets are not directly instantiated by Java code.

How do I include static files within a JSP page?

We can include static files in a JSP page using the JSP include directive. And the inclusion is performed during the translation phase using the following ways:

< % @ include file = “copyright.html” % >

Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.

Why does JComponent have add() and remove() methods but the Component does not?

JComponent has add() and remove() methods because it is a subclass of Container and can contain other Components and JComponents.

What is the difference between custom JSP tags and beans?

Custom tags have access to the implicit objects whereas JavaBeans are normal Java classes and do not know anything about JSP. Custom tags are defined in relatively self-contained behavior whereas JavaBeans are defined in one servlet and can be used in a different servlet or JSP pages.

How do you restrict page errors display on the JSP page?

Set the “Errorpage” attribute of the PAGE directory to the name of the error page in your JSP page. The set “isErrorpage=TRUE” in the error JSP page. So it will automatically call the error page when an error occurs on the JSP page.

How do I perform browser redirection from a JSP page?

We can perform browser redirection from a JSP page using page redirect. We can call redirect pages using the sendRedirect() method in the JSP on client-side request and can be used within the server or outside the server.

Can a JSP page process HTML FORM data?

Yes, a JSP page process HTML FORM data and we don’t require to implement HTTP-protocol specific methods. We can directly obtain the data from the FORM input elements within a scriptlet or expressions.

How does a servlet communicate with a JSP page?

This is one of the frequently asked JSP Interview Questions. Servlet can communicate by using the RequestDispatcher mechanism with a JSP page. It is the process that hands over the request to another web component.

What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?

Request.getRequetsDispatcher() can be used for referring to local servlets within a single web app whereas context.getRequestDispatcher() can be used for referring servlets from other web applications deployed on the same server.

Why is _jspService() method starting with an ‘_’ while other life cycle methods do not?

_jspService() method will be written by the container hence any methods which are not to be overridden by the end-user are typically written starting with an ’_’. This is the reason why we don’t override the _jspService() method on any JSP page.

How can my application get to know when a HttpSession is removed?

Define a Class HttpSessionNotifier which implements HttpSessionBindingListner and implement the functionality what you need in valueUnbound() method. Create an instance of that class and put that instance in HttpSession.

How JSP include directive different from JSP included action?

This is one of the frequently asked JSP Interview Questions and Answers. The Include directives include the file at the run time whereas include action includes the file at run-time. We can pass the parameters to the included page by using a param tag while using an include action tag whereas it is not possible to include directives.

Here, in this article, I discussed the most frequently asked top 100 JSP Interview Questions and Answers. I hope you enjoy this JSP Interview Questions and Answers article. If you have any questions that we have not added here, then please comment your question in the comment box and as soon as possible we will give an answer to that question. Further, if you want to add any JSP Interview Questions with Answers, then please add the same in the comment box which will be beneficial to others.

Leave a Reply

Your email address will not be published. Required fields are marked *