JSP Life Cycle

JSP’s life cycle can be grouped into following phases.

1. JSP Page Translation:

A java servlet file is generated from the JSP source file. This is the first step in its tedious multiple phase life cycle. In the translation phase, the container validates the syntactic correctness of the JSP pages and tag files. The container interprets the standard directives and actions, and the custom actions referencing tag libraries used in the page.

2. JSP Page Compilation:

The generated java servlet file is compiled into a java servlet class.

Note: The translation of a JSP source page into its implementation class can happen at any time between initial deployment of the JSP page into the JSP container and the receipt and processing of a client request for the target JSP page.

3. Class Loading:

The java servlet class that was compiled from the JSP source is loaded into the container.

4. Execution phase:

In the execution phase the container manages one or more instances of this class in response to requests and other events.

The interface JspPage contains jspInit() and jspDestroy(). The JSP specification has provided a special interface HttpJspPage for JSP pages serving HTTP requests and this interface contains _jspService().

5. Initialization:

jspInit() method is called immediately after the instance was created. It is called only once during JSP life cycle.

6. _jspService() execution:

This method is called for every request of this JSP during its life cycle. This is where it serves the purpose of creation. Oops! it has to pass through all the above steps to reach this phase. It passes the request and the response objects. _jspService() cannot be overridden.

7. jspDestroy() execution:

This method is called when this JSP is destroyed. With this call the servlet serves its purpose and submits itself to heaven (garbage collection). This is the end of jsp life cycle.

jspInit(), _jspService() and jspDestroy() are called the life cycle methods of the JSP.

Java Server Pages (JSP) Interview Questions

Question 1: Which of the following is not a standard method called as part of the JSP life cycle?

Answer: jspService()

 

Question 2: If you want to override a JSP file’s initialization method, within what type of tags must you declare the method?

Answer: <%! %>

 

Question 3: Which can not be used as the scope when using a JavaBean with JSP?

Answer:  Response is not a valid object scope for JavaBeans

 

Question 4: Why use RequestDispatcher to forward a request to another resource, instead of using a sendRedirect

Answer: The RequestDispatcher does not require a round trip to the client, and thus is more efficient and allows the server to maintain request state.

 

Question 5: What is the key difference between using a <jsp:forward> and HttpServletResponse.sendRedirect()?

Answer: forward executes on the server while sendRedirect() executes on the client.

 

Question 6: How you  makes your compiled JSP page implement the SingleThreadModel interface?

Answer: <%@ page isThreadSafe=”false” %>

 

Question 7: What is the difference between doing an include or a forward with a RequestDispatcher?

 Answer: When the forward method is used, the invoking resource does not regain control. Multiple include invocations can be made from the same resource, while the invoking resource maintains execution control.

 

Question 8: When a JSP page is compiled, what is it turned into?

Answer: Servlet

 

Question 9: What is JavaServer Pages technology?

Answer: JavaServer Pages (JSP) technology provides a simplified, fast way to create web pages that display dynamically generated content. The JSP specification, developed through an industry-wide initiative led by Sun Microsystems, defines the interaction between the server and the JSP page, and describes the format and syntax of the page.

 

Question 10: How does the JavaServer Pages technology work?

Answer: JSP pages use XML tags and scriptlets written in the JavaTM programming language to encapsulate the logic that generates the content for the page. It passes any formatting (HTML or XML) tags directly back to the response page. In this way, JSP pages separate the page logic from its design and display.

 

JSP technology is part of the Java technology family; it uses a Java programming language-based scripting language, and JSP pages are compiled into servlets. JSP pages may call JavaBeansTM components (beans) or Enterprise JavaBeansTM components (enterprise beans) to perform processing on the server. As such, JSP technology is a key component in a highly scalable architecture for web-based applications.

 

JSP pages are not restricted to any specific platform or web server. The JSP specification represents a broad spectrum of industry input.

 

Question 11: Why do I need JSP technology if I already have servlets?

Answer: JSP pages are compiled into servlets, so theoretically you could write servlets to support your web-based applications. However, JSP technology was designed to simplify the process of creating pages by separating web presentation from web content. In many applications, the response sent to the client is a combination of template data and dynamically-generated data. In this situation, it is much easier to work with JSP pages than to do everything with servlets.

 

Question 12: What is a JSP page?

Answer: A JSP page is a page created by the web developer that includes JSP technology-specific tags, declarations, and possibly scriptlets, in combination with other static (HTML or XML) tags. A JSP page has the extension .jsp; this signals to the web server that the JSP engine will process elements on this page.

 

Question 13: How do JSP pages work?

Answer: A JSP engine interprets tags and scriptlets, and generates the content required – for example, by calling a bean, accessing a database with the JDBCTM API or including a file. It then sends the results back in the form of an HTML (or XML) page to the browser. The logic that generates the content is encapsulated in tags and beans processed on the server. JSP scriptlets let developers tie everything together, and ordinary HTML tags control the formatting and display of the generated page.

 

Question 14: How is a JSP page invoked and compiled?

Answer: Pages built using JSP technology are typically implemented using a translation phase that is performed once, the first time the page is called. The page is compiled into a Java Servlet class and remains in server memory, so subsequent calls to the page have very fast response times.

 

Question 15: Can I create XML pages using JSP technology?

Answer: Yes, the JSP specification does support creation of XML documents. For simple XML generation, the XML tags may be included as static template portions of the JSP page. Dynamic generation of XML tags occurs through bean components or custom tags that generate XML output. See the white paper Developing XML Solutions with JavaServer Pages Technology (PDF) for details.

 

Question 16: Can I generate and manipulate JSP pages using XML tools?

Answer: The JSP 1.1 specification describes a mapping between JSP pages and XML documents.The mapping enables the creation and manipulation of JSP pages using XML tools.

 

Question 17: How do I use JavaBeans components (beans) from a JSP page?

Answer: The JSP specification includes standard tags for bean use and manipulation. The useBean tag creates an instance of a specific JavaBeans class. If the instance already exists, it is retrieved. Otherwise, it is created. The setProperty and getProperty tags let you manipulate properties of the given object. These tags are described in more detail in the JSP specification and tutorial.

 

Question 18: Why are there no try/catch blocks around my JSP scriptlets? I know the code should throw errors.

Answer: Don’t be confused. Scriplets do eventually end up with try/catch blocks around thier code. A JSP will catch any thrown error and display it to a user, or optionally handle it with a error page if specified.

 

If you would like to see the error handling examine the generated code by your JSP container.

 

Question 19: How do I call a function in my JSP via client-side JavaScript?

Answer: It is not possible to do that.

 

A common misconception about JSP is where it takes place. JSP occurs only on the server-side. As it implies, client-side JavaScript takes place only on the client’s computer. You cannont interchange the two.

 

Question 20: What are Implicit Objects?

Answer. An implicit object is available for a JSP developer to use inside scriptlets and expressions. The implicit objects represent all of the important components of the PageContext. Implicit objects need not be declared. They already exist and an error will be thrown if another variable of the same name is used.

 

User friendly documentaion of the implicit objects along with code examples is also provided at JSP Insider. Here is a list of the JSP 1.1 implicit objects and links for the documentation provided by JSP Insider.

 

A. pageContext

B. application

C. out

D. response

E. request

F: Session

 

Question 21: Is it possible to pass in any Object other than a String to a taglib?

Answer. Yes, just use an expression. The value of the expression will not be converted to a string in this case.

Take the following example

<example:tag date=”<%= new java.util.Date()%>” />

In the above example, the corresponding tag handler will have the setDate method called with a java.util.Date object passed in as a parameter.

This is perfectly valid in your JSP assuming the tag’s value can be a runtime expression. The TLD for this taglibrary would have to include the following snippet.

<attribute>

<name>date</name>

<rtexprvalue>true</rtexprvalue>

</attribute>

Question 22: Both <%!…%> and <%…%> can be used for declaring variables. What is the difference between both and which to use?

Answer: There is a distinct difference between an declaration, <%!…%>, and a scriptlet, <%…%>.

 

<%!…%> Declares a variable or method valid in the scripting language used in the JSP page.

<%…%> Contains a code fragment valid in the pages scripting language.

 

The big difference is that <%…%> is initialized once per each request to the JSP. Often the <%…%> is prefered and recommended for this reason, variables declared by <%!…%> are only loaded once, at the beginning of the JSP’s lifecycle.

Question 23: What JSP servers are currently available?

Answer: Here’s a list of JSP servers with which we are familiar. This is only a partial list.

Extreme Internet Server

IPlanet WebServer

JRun

Orion

Resin

Tomcat

WebLogic

WebSphere

ServletExec

LiteWebServer

For a more complete list check out the Java server list at the Java Skyline web site. This list contains more than just JSP servers, but it is a great place to start.

Question 24: How do I Pass an Object between a Servlet and a JSP?

Answer: On the server-side you may forward the request with, pageContext.forward(“Relative URI…”); for a JSP, or with getServletConfig().getServletContext().getRequestDispatcher(“Relative URI…”).forward(request, response); for a Servlet. The same HttpServletRequest object is shared when using these methods. Because of this objects may be stashed and retrieved using the getAttribute() and setAttribute() methods of HttpServletRequest.

 

Take for example the following Servlet. A java.lang.String object is set in the request object with “text” as the key. The servlet then fowards to a JSP.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ExampleServlet extends HttpServlet 
{
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException   
  {
   String text  = new String("Some text to pass...");
   request.setAttribute("text", text);
   getServletConfig().getServletContext().getRequestDispatcher("/test.jsp").forward(request, response);

  }
}

 

Using getAttribute(), a JSP can access the object set by the servlet.

 

1
2
3
4
5
6
7
8
9
10
<html>
 <head><title>Passing an object.</title></head>
 <body>
<%
  String text = (String)request.getAttribute("text");
%>
<%= text %>
 </body>
</html>

 

If the result would be a webpage displaying, “Some text to pass…”

 

Any object may be passed using this method. Just remember to use the appropriate type cast when getting the object from the request. This method may also be used to pass objects between only servlets or JSP.

 

Question 25: How can I set a cookie in JSP?

Answer: This should work:

 

response.setHeader(“Set-Cookie”, “cookie string”);

To give the response-object to a bean, write a method setResponse

(HttpServletResponse response)

– to the bean, and in jsp-file:

 

<%

bean.setResponse (response);

%>

 

Question 26: How can I include one JSP inside another JSP?

Answer: <%@ include=”FileName.jsp” %>

Question 27: How do I delete a cookie with JSP?

Answer:

<%

Cookie killCookie = new Cookie(“foo”, null);

killCookie.setPath(“/”);

killCookie.setMaxAge(0);

response.addCookie(killCookie);

%>

 

Question 28: What is a web application?

Answer: A web application is a collection of resources that is mapped to a specific Uniform Resource Identifier (URI) prefix. These resources may include JSP pages, Servlets, HTML files, and images.

 

Question 29: If you want to override a JSP file’s initialization method, within what type of tags must you declare the method?

Answer: <%! %>

 

Question 30: Why use RequestDispatcher to forward a request to another resource, instead of using a sendRedirect?

Answer: The RequestDispatcher does not require a round trip to the client, and thus is more efficient and allows the server to maintain request state.

 

Question 31: What is the key difference between using a <jsp:forward> and HttpServletResponse.sendRedirect()?

Answer: forward executes on the server while sendRedirect() executes on the client.

 

Question 32. What is the difference between doing an include or a forward with a RequestDispatcher?

Answer: When the forward method is used, the invoking resource does not regain control. Multiple include invocations can be made from the same resource, while the invoking resource maintains execution control.

 

Question 33. What are the elements available in JSP?

Answer: There are three types of elements: directive elements, scripting elements, and action elements.

 

Question 34. How do you invoke a JSP page from a servlet?

Answer:

ServletContext context = getServletConfig().getServletContext();

context.getResourceDispatcher(urlpath).forward(request, response);

(Or)

RequestDispatcher rd = request.getRequestDispatcher(urlpath);

rd.forward(request, response);

 

Question 35. Can JSP and Servlet share same Session and Beans?

Answer: Yes

 

Question 36. What are the different scopes available for usebean tag in JSP?

Answer: Page, Request, Session and Application.