Jsp Lifecycle

Jsp Lifecycle
Every JSP Page has a lifecycle, just like a servlet. After all, a JSP Page gets converted into a servlet before it is executed and hence it is obvious that the JSP Page would have a life-cycle. In this chapter, we are going to see just that.

So, lets get started!!!

The JSP Life-Cycle
The JSP page lifecycle is on the exam. A JSP's life starts when it is first requested. The Servlet Container parses the JSP, creates a servlet, runs the servlet, handles responding to the request, and manages servlet persistence. Smart containers place the servlet in memory only once upon the first request to speed up processing.

Though the life of a JSP looks simple, you might find it better if I put it all in a table for you to refer quickly. Well here we are:
JSP Life-Cycle Step Description
Page translation < % = expression % > Translates this to a string. It is equivalent to out.print(expression);.
Page compilation < % yourCode % > Compiles this.
Load class Loads the JSP page's servlet class upon first request.
Create instance Instantiates an instance of the servlet class.
Call jspInit Initializes the servlet instance by calling the jspInit method.
Call _jspService Invokes the _jspService method, passing a request and a response object.
Call jspDestroy If the container needs to remove the JSP page's servlet, it calls the jspDestroy method.
A JSP page is always converted to a servlet. Therefore the lifecycle of a JSP page is largely determined by how the JSP container handles Java servlets.

Each JSP page is eventually converted to a servlet class and then compiled. Each time a request is sent to a JSP page, the container compares the file dates. If the JSP is younger than the servlet, the container recompiles it and then sends the request to the servlet. The compiling process is performed automatically when the server receives a request for that page.

There are two phases of a JSP page's life: translation and execution. In the translation phase, the container starts building the final page, adding contents from any includes and skipping JSP comments (but retaining HTML comments). The container interprets all the Java code, such as directives, actions, and the custom actions referencing tag libraries that occur in the page. Once this is done, the container compiles the result into a servlet class. This completes the translation phase and the servlet is ready to receive requests.

The execution phase involves instantiating request and response objects and invoking the correct servlet based on the request. After the servlet finishes its work, it hands the response object to the container. The container then sends the response back to the client.

JSP tutorial syntax

JSP Syntax:



I feel that it is always useful to take a look at the simple syntactical constructs of a technology before we dig deep into it. Well, whether you agree or disagree, below is a synopsis of the JSP syntax. You can use it to get a feel of what we are going to learn in the next few chapters…



Syntax What it Represents Example
< ! -- comment -- > HTML Comment < ! -- This HTML comment is passed through to the client -- >
<%-- comment --%> JSP Comment <%-- This comment is ignored by the server --%>
<%@ page [key]="[value]" %> Page Directive <%@ page import="java.util.*" %>
<%! Declaration %> Declaration <%! String name = new String ("Rocky"); %>
<%= expression %> Expression Your shopping cart total is: <%= shoppingCart.getTotal() %>.
<% code %> Scriptlet <% String password =request.getParameter("password"); if ( password == null) { %>


Password is required, thank you.

<% } %>

<%@ include file="file" %> Static include, parsed at compile-time <%@ include file="welcome.jsp>
< jsp : include page="file" / > Dynamic include, request-time and not parsed < jsp : include page="welcome.html" / >

Java server pages tutorial

Java server pages tutorial
JSP and Servlets have greatly simplified the life of a J2EE programmer who builds Java based Enterprise Applications for a living. As part of the series of articles on the SCWCD Certification, we have already covered the Servlets in great detail. Next in line is the Java Server Pages Technology also called the JSP Technology

In this chapter and the subsequent many chapters, we will cover the JSP Technology in great detail.

So, lets get started!!!

Introduction to Java Server Pages:

Java Server Pages have become an integral part of any J2EE application. They are used extensively because they can combine the features of HTML and Java. The difficulty level of JSP is half-way between HTML and pure Java. For simple tasks like displaying the current date, you write a normal HTML page and add only a small amount of Java as a scriptlet. For big tasks like processing a shopping cart, you use JSP as the mediator between the Web form and a component (Ex: Servlet) that has all the processing logic.

CGI, Perl, Active Server Pages etc were all the predecessors of Java Server Pages. Am not saying that the JSP Technology was built based on these technologies but it is safe to say that, the JSP Technology was created to overcome many of the shortcomings in the above mentioned technologies. Though the ASP technology is a web server scripting champion and is used very widely, the only problem is the Runs only in Windows Attitude of the technology. Unlike ASP, JSP has equivalent if not better features and can run in any environment making it an invaluable tool for enterprise application developers who don't want to be tied to the limitation of the system running only in Windows.

Not only does JSP run on all major platforms, but the JavaBeans used by these JSPs run on all major platforms as well.

JSP competes directly with ASP. In fact, you would be forgiven if you thought it was a copy. Sun took the same approach to JSP as it did with Java. Sun borrowed the syntax of its best competitor (ASP for JSP and C++ for Java) tweaked it a little, but built everything under the hood from scratch. Java syntax comes from C++, but it works on all platforms with no portability issues like C++ for the developer. Similarly, the JSP structure comes from ASP. The look and feel, and even some syntax is the same. However, ASP primarily uses Microsoft's versatile VBScript, while JSP uses the more powerful and portable Java and JavaScript.

While it helps to know JSP's history, I won't bore you anymore with it. You have learnt as much as you need to know about the history of Java Server Pages and it is time to move on to the Exam Objectives…

How Does JSP Work?

If you remember the initial chapters in this series, you would remember the fact that JSP Pages get converted or rather Translated into Servlets before execution. Kudos to you if you remembered it. The JSP container parses the JSP source and converts the entire JSP page (HTML becomes strings and Java source code embedded in a JSP page gets copied into methods) into a Java servlet class. The HTML text is converted into a bunch of out.println statements in the order encountered. Finally, the container compiles this class into Java bytecodes. This Servlet is invoked by the Server in order to finish displaying the contents on the web browser.

What is JSP tag handler ?

What is JSP tag handler ?
A Java programming language object that implements the behavior of a custom tag.
If you have any questions that you want answer for - please leave a comment on this page and I will answer them.

If you have any more questions on JSPs that you have faced during your interviews and wish to add them to this collection - pls drop a note to anandvijayakumar007@gmail.com and I shall be glad to add them to this list.

What is JSP tag file ?

What is JSP tag file ? 
A source file containing a reusable fragment of JSP code that is translated into a tag handler when a JSP page is translated into a servlet.

What is JSP scriptlet ?

What is JSP scriptlet ? 
A JSP scripting element containing any code fragment that is valid in the scripting language used in the JSP page. The JSP specification describes what is a valid scriptlet for the case where the language page attribute is "java".

What is JSP scripting element ?

What is JSP scripting element ? 
A JSP declaration, scriptlet, or expression whose syntax is defined by the JSP specification and whose content is written according to the scripting language used in the JSP page. The JSP specification describes the syntax and semantics for the case where the language page attribute is "java".

What is JSP page ?

A text-based document containing static text and JSP elements that describes how to process a request to create a response. A JSP page is translated into and handles requests as a servlet.

JSP expression language ?

What is JSP expression language ?
A language used to write expressions that access the properties of JavaBeans components. EL expressions can be used in static text and in any standard or custom tag attribute that can accept an expression.

What is JSP expression ?

What is JSP expression ? 
A scripting element that contains a valid scripting language expression that is evaluated, converted to a String, and placed into the implicit out object.

What is JSP element ?

What is JSP element ? 
A portion of a JSP page that is recognized by a JSP translator. An element can be a directive, an action, or a scripting element.

What is JSP document ?

What is JSP document ?
A JSP page written in XML syntax and subject to the constraints of XML documents. 

What is JSP directive ?

What is JSP directive ?
A JSP element that gives an instruction to the JSP container and is interpreted at translation time. 

What is JSP declaration ?

What is JSP declaration ? 
A JSP scripting element that declares methods, variables, or both in a JSP page

What is JSP custom tag ?

What is JSP custom tag ?
A tag that references a JSP custom action

What is JSP custom action ?

What is JSP custom action ?
A user-defined action described in a portable manner by a tag library descriptor and imported into a JSP page by a taglib directive. Custom actions are used to encapsulate recurring tasks in writing JSP pages.

What is JSP container ?

What is JSP container ?
A container that provides the same services as a servlet container and an engine that interprets and processes JSP pages into a servlet.

What is JavaServer Pages Standard Tag Library (JSTL) ?

What is JavaServer Pages Standard Tag Library (JSTL) ? 
A tag library that encapsulates core functionality common to many JSP applications. JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization and locale-specific formatting tags, SQL tags, and functions.

How will you handle the runtime exception in your jsp page?

How will you handle the runtime exception in your jsp page?
The errorPage attribute of the page directive can be used to catch run-time exceptions automatically and then forwarded to an error processing page. You can define the error page to which you want the request forwarded to, in case of an exception, in each JSP Page. Also, there should be another JSP that plays the role of the error page which has the flag isErrorPage set to True. 

How can you prevent the Browser from Caching data of the Pages you visit?

How can you prevent the Browser from Caching data of the Pages you visit?
By setting properties that prevent caching in your JSP Page. They are:
<% response.setHeader("pragma","no-cache");//HTTP 1.1 response.setHeader("Cache-Control","no-cache"); response.setHeader("Cache-Control","no-store"); response.addDateHeader("Expires", -1); response.setDateHeader("max-age", 0); //response.setIntHeader ("Expires", -1); //prevents caching at the proxy server response.addHeader("cache-Control", "private"); %>

What is JSP translation?

What is  JSP translation?
JSP translation is an action that refers to the convertion of the JSP Page into a Java Servlet. This class is essentially a servlet class wrapped with features for JSP functionality.

Extend JSP technology?

Extend JSP technology?
Yes. JSP technology lets the programmer to extend the jsp to make the programming more easier. JSP can be extended and custom actions & tag libraries can be developed to enhance/extend its features.

Understanding by context initialization parameters?

Understanding by context initialization parameters?
The context-param element contains the declaration of a web application's servlet context initialization parameters.
namevalue
The Context Parameters page lets you manage parameters that are accessed through the ServletContext.getInitParameterNames and ServletContext.getInitParameter methods.

Role of JSP in MVC Model?

Role of JSP in MVC Model?
JSP is mostly used to develop the user interface, It plays are role of View in the MVC Model.

What are JSP Custom tags?

What are JSP Custom tags?
JSP Custom tags are user defined JSP language elements. JSP custom tags are user defined tags that can encapsulate common functionality. For example you can write your own tag to access the database and performing database operations. You can also write custom tags to encapsulate both simple and complex behaviors in an easy to use syntax. The use of custom tags greatly enhances the functionality and simplifies the readability of JSP pages.

Life-cycle methods of JSP?

Life-cycle methods of JSP?
Life-cycle methods of the JSP are:

a) jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance.

b)_jspService(): The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method cann't be overridden.

c) jspDestroy(): The container calls this when its instance is about to destroyed.
The jspInit() and jspDestroy() methods can be overridden within a JSP page.

What is a JSP Scriptlet?

What is a JSP Scriptlet?
JSP Scriptlets is a term used to refer to pieces of Java code that can be embedded in a JSP PAge. Scriptlets begins with <% tag and ends with %> tag. Java code written inside scriptlet executes every time the JSP is invoked. 

Types of comments are available in the JSP?

Types of comments are available in the JSP?
There are two types of comments that are allowed in the JSP. They are hidden and output comments.

A hidden comment does not appear in the generated HTML output, while output comments appear in the generated output.

Example of hidden comment:
< % - - This is a hidden comment - - % >

Example of output comment:
< ! - - This is an output comment - - >

What is expression in JSP?

What is expression in JSP?
Expression tag is used to insert Java values directly into the output.
Syntax for the Expression tag is: <%= 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. The most commonly used language is regular Java.

What are JSP Output Comments?

What is JSP Output Comments?
JSP Output Comments are the comments that can be viewed in the HTML source file. They are comments that are enclosed within the < ! - - Your Comments Here - - > 

Different scope values for the < jsp : useBean > tag?

Different scope values for the < jsp : useBean > tag?
< jsp : useBean > tag is used to use any java object in the jsp page. Here are the scope values for < jsp : useBean > tag:
a) page
b) request
c) session and
d) application

Implicit Objects available to the JSP Page?

Implicit Objects available to the JSP Page?
Implicit objects are the objects available to the JSP page. These objects are created by Web container and contain information related to a particular request, page, or application. The JSP implicit objects are:
application
config
exception
out
page
pageContext
request
response and
session

Advantage of JSP over Servlets?

Advantage of JSP over Servlets?
Can contain HTML, JavaScript, XML and Java Code whereas Servlets can contain only Java Code, making JSPs more flexible and powerful than Servlets.

However, Servlets have their own place in a J2EE application and cannot be ignored altogether. They have their strengths too which cannot be overseen.

Difference between < jsp : forward page = ... > and response.sendRedirect(url)?

Difference between < jsp : forward page = ... > and response.sendRedirect(url)?
The element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file.

 

Difference between < jsp : include page = ... > and < % @ include file = ... >?

Difference between < jsp : include page = ... > and < % @ include file = ... >?
Both the tags include information from one JSP page in another. The differences are:

< jsp : include page = ... >

This is like a function call from one jsp to another jsp. It is executed ( the included page is executed and the generated html content is included in the content of calling jsp) each time the client page is accessed by the client. This approach is useful while modularizing a web application. If the included file changes then the new content will be included in the output automatically.

< % @ include file = ... >

In this case the content of the included file is textually embedded in the page that have < % @ include file=".."> directive. In this case when the included file changes, the changed content will not get included automatically in the output. This approach is used when the code from one jsp file required to include in multiple jsp files.
 

What are jsp actions?

 What are jsp actions?
JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of "jsp" followed by a colon, followed by the action name followed by one or more attribute parameters.

There are six JSP Actions:
< jsp : include / >
< jsp : forward / >
< jsp : plugin / >
< jsp : usebean / >
< jsp : setProperty / >
< jsp : getProperty / >

What is JSP?

What is JSP?
JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to web applications in a portable, secure and well-defined way. The JSP Technology allows us to use HTML, Java, JavaScript and XML in a single file to create high quality and fully functionaly User Interface components for Web Applications. 

Jsp Interview Questions

Jsp Interview Questions
1)What is JSP?
2) What do you understand by JSP Actions?
3) What is the difference between < jsp : include page = ... > and < % @ include file = ... >?
4) What is the difference between < jsp : forward page = ... > and response.sendRedirect(url)?
5) Name one advantage of JSP over Servlets?
6) What are implicit Objects available to the JSP Page?
7)What are all the different scope values for the < jsp : useBean > tag?
8)What is JSP Output Comments?
9. What is expression in JSP?
10. What types of comments are available in the JSP?
11. What is a JSP Scriptlet?
 12. What are the life-cycle methods of JSP?
13. What are JSP Custom tags?
14. What is the role of JSP in MVC Model?
15. What do you understand by context initialization parameters?
16. Can you extend JSP technology?
17. What do you understand by JSP translation?
18. How can you prevent the Browser from Caching data of the Pages you visit?
19. How will you handle the runtime exception in your jsp page?
20. What is JavaServer Pages Standard Tag Library (JSTL) ?
21. What is JSP container ?
22. What is JSP custom action ?
23. What is JSP custom tag ?
24. What is JSP declaration ?
25. What is JSP directive ?
26. What is JSP document ?
27. What is JSP element ?
28. What is JSP expression ?
29. What is JSP expression language ?
30. What is JSP page ?
31. What is JSP scripting element ?
32. What is JSP scriptlet ?
33. What is JSP tag file ?
34. What is JSP tag handler ?      
 
 
Top Blogs