You are on page 1of 16

What is JSP LifeCycle?

JSP Life Cycle is defined as translation of JSP Page into servlet as a JSP Page needs
to be converted into servlet first in order to process the service requests. The Life
Cycle starts with the creation of JSP and ends with the disintegration of that.
Different phases of JSP Life Cycle
When the browser asks for a JSP, JSP engine first checks whether it needs to compile
the page. If the JSP is last compiled or the recent modification is done in JSP, then the
JSP engine compiles the page.
Compilation process of JSP page involves three steps:
 Parsing of JSP
 Turning JSP into servlet
 Compiling the servlet
JSP Lifecycle is depicted in the below diagram.
Following steps explain the JSP life cycle:
1. Translation of JSP page
2. Compilation of JSP page(Compilation of JSP page into
_jsp.java)
3. Classloading (jsp.java is converted to class file jsp.class)
4. Instantiation(Object of generated servlet is created)
5. Initialisation(jspinit() method is invoked by container)
6. Request Processing(jspservice() method is invoked by the
container)
7. Destroy (_jspDestroy() method invoked by the container)
Let us have more detailed summary on the above points:
1. Translation of the JSP Page:
A Java servlet file is generated from a JSP source file. This is the first step of JSP life
cycle. In translation phase, container validates the syntactic correctness of JSP page
and tag files.
 The JSP container interprets the standard directives and actions, and the custom
actions referencing tag libraries (they are all part of JSP page and will be
discussed in the later section) used in this JSP page.
 In the above pictorial description, demo.jsp is translated to demo_jsp.java in the
first step
 Let's take an example of "demo.jsp" as shown below:
Demo.jsp
1. <html>
2. <head>
3. <title>Demo JSP</title>
4. </head>
5. <%
6. int demvar=0;%>
7. <body>
8. Count is:
9. <% Out.println(demovar++); %>
10. <body>
11. </html>

Code Explanation for Demo.jsp


Code Line 1: html start tag
Code Line 2: Head tag
Code Line 3 - 4: Title Tag i.e. Demo JSP and closing head tag
Code Line 5,6: Scriptlet tag wherein initializing the variable demo
Code Line 7 - 8: In body tag, a text to be printed in the output (Count is: )
Code Line 9: Scriplet tag where trying to print the variable demovar with
incremented value
Code Line 10-11: Body and HTML tags closed
Demo JSP Page is converted into demo_jsp servlet in the below code.

Code explanation for Demo_jsp.java


Code Line 1: Servlet class demo_jsp is extending parent class HttpServlet
Code Line 2,3: Overriding the service method of jsp i.e. _jspservice which has
HttpServletRequest and HttpServletResponse objects as its parameters
Code Line 4: Opening method
Code Line 5: Calling the method getWriter() of response object to get
PrintWriterobject (prints formatted representation of objects to text output stream)
Code Line 6: Calling setContentType method of response object to set the content
type
Code Line 7: Using write () method of PrintWriter object trying to parse html
Code Line 8: Initializing demovar variable to 0
Code Line 9: Calling write() method of PrintWriter object to parse the text
Code Line 10: Calling print() method of PrintWriter object to increment the variable
demovar from 0+1=1.Hence, the output will be 1
Code Line 11: Using write() method of PrintWriter object trying to parse html
Output:

 Here you can see that in the screenshot theOutput is 1 because demvar is
initialized to 0 and then incremented to 0+1=1
In the above example,
 demo.jsp, is a JSP where one variable is initialized and incremented. This JSP
is converted to the servlet (demo_jsp.class ) wherein the JSP engine loads the
JSP Page and converts to servlet content.
 When the conversion happens all template text is converted to println()
statements and all JSP elements are converted to Java code.
This is how a simple JSP page is translated into a servlet class.
2. Compilation of the JSP Page
 The generated java servlet file is compiled into java servlet class
 The translation of java source page to its implementation class can happen at
any time between the deployment of JSP page into the container and processing
of the JSP page.
 In the above pictorial description demo_jsp.java is compiled to a class file
demo_jsp.class
3. Classloading
 Servlet class that has been loaded from JSP source is now loaded into the
container
4. Instantiation
 In this step the object i.e. the instance of the class is generated.
 The container manages one or more instances of this class in the response to
requests and other events. Typically, a JSP container is built using a servlet
container. A JSP container is an extension of servlet container as both the
container support JSP and servlet.
 A JSPPage interface which is provided by container provides init() and destroy
() methods.
 There is an interface HttpJSPPage which serves HTTP requests, and it also
contains the service method.
5. Initialization
6. public void jspInit()
7. {
8. //initializing the code
}
 _jspinit() method will initiate the servlet instance which was generated from
JSP and will be invoked by the container in this phase.
 Once the instance gets created, init method will be invoked immediately after
that
 It is only called once during a JSP life cycle, the method for initialization is
declared as shown above
6. Request processing
7. void _jspservice(HttpServletRequest request HttpServletResponse response)
8. {
9. //handling all request and responses
}
 _jspservice() method is invoked by the container for all the requests raised by
the JSP page during its life cycle
 For this phase, it has to go through all the above phases and then only service
method can be invoked.
 It passes request and response objects
 This method cannot be overridden
 The method is shown above: It is responsible for generating of all HTTP
methods i.eGET, POST, etc.
7. Destroy
8. public void _jspdestroy()
9. {
10. //all clean up code
}
 _jspdestroy() method is also invoked by the container
 This method is called when container decides it no longer needs the servlet
instance to service requests.
 When the call to destroy method is made then, the servlet is ready for a garbage
collection
 This is the end of the life cycle.
 We can override jspdestroy() method when we perform any cleanup such as
releasing database connections or closing open files
4
Understanding Context… seeking to understand the
issues, opportunities or situation from multiple
perspectives….
There are many different approaches for seeking to understand the context
in which programming is being developed and delivered. No one way is
right… rather certain approaches may be selected based on your focus and
resources. Below are brief descriptions of various approaches. Many of
these approaches can be mixed and matched!
Needs assessment is a specific approach that focuses on the systematic
collection of data from stakeholders related to their needs or perceived needs.
There are various methods that can be used to conduct a needs assessment.
What holds them together conceptually is that the guiding questions for the
investigation are framed around potential participant “needs.” Needs assessment
is often used as a general and universal term for data collection related to
program planning, however like all approaches, it is has strengths and
limitations.

Situational analysis is a general term used to describe an effort to broadly


describe an existing set of conditions. There are various methods that can be
used to conduct a situational analysis, and they tend to include a look at the
following general categories: social relations, environment, economics, and
policy.
Ripple effect mapping is an approach to visualizing the ripple effects of
programmatic effort. If you think of dropping a stone in a pond… the ripples
move out in all directions from the original point of contact. There are various
tools for mapping ripple effects, some low tech and others high tech.
Power analysis is an approach to understanding and articulating the power
relations and dynamics amongst a group of people. Power analyses can work at
different scales, including organizational. Power mapping can be helpful in
understanding the context of social relations within an organization, network,
coalition or community.
Partner-network mapping is a way to draw out and describe the relationships
amongst and between important players or partners in a network or coalition.
For example, the Farmer-to-Farmer program has used ‘host-relational’ maps to
draw out and build common understanding of the ways the program is touching
and engaging others in its network. It defines the network, the players in the
network, and the ways in which their efforts are related.
Asset-mapping is a strengths-based approach to understanding context and
fundamentally differs in it framing from “needs” assessment. The idea with asset
mapping is to uncover and engage the assets in a particular community toward
the end of desired change or effect.
Civil Rights reviews are analyses of the current state of affairs with regard to
inclusion, access and civil rights compliance in the context of programmatic
effort. Review data can help us understand who is being reached, who is not
being reached and context around both.
System mapping is a way to develop a shared mental model amongst
collaborators around core concepts in a programmatic or change effort. Using
DSRP, collaborators can map the distinctions, relationships, perspectives and
parts of an over-arching system.
Demographic mapping is a way to make visible the sometimes not visible
patterns of social identity and location within a specific geography. Using
Census data, as well as other data sources, we can better understand the
social/spatial contexts in which we program
Art of Hosting is an approach to convening/hosting conversations that allow for
the emergence of important issues and opportunities within a community.
Gap analysis involves the review of current conditions related to where their
might be gaps in programmatic response to a set of issues or opportunities.
There are a variety of ways to investigate where current programmatic or
participant group gaps exist.

3
Session

A session creates a file in a temporary directory on the server where registered session variables
and their values are stored. This data will be available to all pages on the site during that visit.

A session ends when the user closes the browser or after leaving the site, the server will terminate
the session after a predetermined period of time, commonly 30 minutes duration.

Cookies

Cookies are text files stored on the client computer and they are kept of use tracking purpose.
Server script sends a set of cookies to the browser. For example name, age, or identification number
etc. The browser stores this information on a local machine for future use.

When next time browser sends any request to web server then it sends those cookies information to
the server and server uses that information to identify the user.

2
Request Redirects
A redirect is a way to forward visitors and search engines from one URL to another.
This is useful when moving content to a new URL, when deleting pages or when
changing domain names or merging websites.

Whenever possible avoid using redirects, but when you have to use them, make sure
to follow these best practices:

 Avoid chained redirects: one redirect should not forward to another redirect.
 Redirect to the preferred version of your website, using the right protocol (http or
https), domain name (www or non-www) and path notation (with or without
trailing slash).
 Use a 302-redirect for inactive campaigns.
 Use a 301-redirect for content that's permanently removed.

Persistence
Definition - What does Persistence mean?
Persistence refers to object and process characteristics that continue to exist even after
the process that created it ceases or the machine it is running on is powered off. When
an object or state is created and needs to be persistent, it is saved in a non-volatile
storage location, like a hard drive, versus a temporary file or volatile random access
memory (RAM).

[NEW] Techopedia Resources | Browse Industry Leading Software Used by Techopedia Staff and Users
Daily

Techopedia explains Persistence


In terms of data, persistence means an object should not be erased unless it is really
meant to be deleted. This entails proper storage and certain measures that allow the
data to persist. In terms of computer threads and processes, a persistent process is one
that cannot be killed or shut down. This is usually true for core system processes that
are essential to a properly functioning system.
For example, even if a Windows operating system (OS) explorer fails or is killed, it
simply restarts. A persistent state refers to the retention of that state, even after the
process has been killed. In this case, the state is saved in persistent storage before
device shutdown and then reloaded when the device turns on, ensuring that the device,
workspace or data are in the same state after turning on the device.
This definition was written in the context of Computing
RequestDispatcher in Servlet
1. RequestDispatcher Interface
2. Methods of RequestDispatcher interface
1. forward method
2. include method
3. How to get the object of RequestDispatcher
4. Example of RequestDispatcher interface

The RequestDispatcher interface provides the facility of dispatching the request to another
resource it may be html, servlet or jsp. This interface can also be used to include the
content of another resource also. It is one of the way of servlet collaboration.

There are two methods defined in the RequestDispatcher interface.

Methods of RequestDispatcher interface


The RequestDispatcher interface provides two methods. They are:

1. public void forward(ServletRequest request,ServletResponse


response)throws ServletException,java.io.IOException:Forwards a request
from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
2. public void include(ServletRequest request,ServletResponse
response)throws ServletException,java.io.IOException:Includes the content of
a resource (servlet, JSP page, or HTML file) in the response.
As you see in the above figure, response of second servlet is sent to the client. Response of
the first servlet is not displayed to the user.
As you can see in the above figure, response of second servlet is included in the response of the first ser
being sent to the client.

How to get the object of RequestDispatcher


The getRequestDispatcher() method of ServletRequest interface returns the object of
RequestDispatcher. Syntax:

Syntax of getRequestDispatcher method


1. public RequestDispatcher getRequestDispatcher(String resource);
Example of using getRequestDispatcher method
1. RequestDispatcher rd=request.getRequestDispatcher("servlet2");
2. //servlet2 is the url-pattern of the second servlet
3.
4. rd.forward(request, response);//method may be include or forward

Example of RequestDispatcher interface


In this example, we are validating the password entered by the user. If password is servlet,
it will forward the request to the WelcomeServlet, otherwise will show an error message:
sorry username or password error!. In this program, we are cheking for hardcoded
information. But you can check it to the database also that we will see in the development
chapter. In this example, we have created following files:

o index.html file: for getting input from the user.


o Login.java file: a servlet class for processing the response. If password is servet, it
will forward the request to the welcome servlet.
o WelcomeServlet.java file: a servlet class for displaying the welcome message.
o web.xml file: a deployment descriptor file that contains the information about the
servlet.

1
JavaScript
JavaScript is a programming language commonly used in web
development. It was originally developed by Netscape as a means to
add dynamic and interactive elements to websites. While JavaScript is
influenced by Java, the syntax is more similar to C and is based on
ECMAScript, a scripting language developed by Sun Microsystems.
JavaScript is a client-side scripting language, which means the source
code is processed by the client's web browser rather than on the web
server. This means JavaScript functions can run after a webpage has
loaded without communicating with the server. For example, a
JavaScript function may check a web form before it is submitted to
make sure all the required fields have been filled out. The JavaScript
code can produce an error message before any information is actually
transmitted to the server.
Like server-side scripting languages, such as PHP and ASP, JavaScript
code can be inserted anywhere within the HTML of a webpage.
However, only the output of server-side code is displayed in the HTML,
while JavaScript code remains fully visible in the source of the
webpage. It can also be referenced in a separate .JS file, which may
also be viewed in a browser.
Below is an example of a basic JavaScript function that adds two
numbers. The function is called with the parameters 7 and 11. If the
code below were included in the HTML of a webpage, it would display
the text "18" in an alert box.
<script>
function sum(a,b)
{
return a + b;
}
var total = sum(7,11);
alert(total);
</script>

JavaScript functions can be called within <script> tags or when


specific events take place. Examples include onClick, onMouseDown,
onMouseUp, onKeyDown, onKeyUp, onFocus, onBlur, onSubmit, and
many others. While standard JavaScript is still used for performing
basic client-side functions, many web developers now prefer to use
JavaScript libraries like jQuery to add more advanced dynamic
elements to websites.

Request Type
PropertiesSection
Request.cache Read only

Contains the cache mode of the request (e.g., default, reload, no-cache).
Request.context Read only

Contains the context of the request (e.g., audio, image, iframe, etc.)
Request.credentials Read only

Contains the credentials of the request (e.g., "omit", "same-origin", "include"). The
default is "same-origin".
Request.destination Read only

Returns a string from the RequestDestination enum describing the request's destination.
This is a string indicating the type of content being requested.
Request.headers Read only

Contains the associated Headers object of the request.


Request.integrity Read only

Contains the subresource integrity value of the request (e.g., sha256-


BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).

Request.method Read only

Contains the request's method (GET, POST, etc.)


Request.mode Read only

Contains the mode of the request (e.g., cors, no-cors, same-origin, navigate.)
Request.redirect Read only

Contains the mode for how redirects are handled. It may be one of follow, error,
or manual.
Request.referrer Read only

Contains the referrer of the request (e.g., client).


Request.referrerPolicy Read only

Contains the referrer policy of the request (e.g., no-referrer).


Request.url Read only

Contains the URL of the request.

Request implements Body, so it also inherits the following properties:


body Read only

A simple getter used to expose a ReadableStream of the body contents.


bodyUsed Read only

Stores a Boolean that declares whether the body has been used in a response yet.
Life cycle is same as question no 5

You might also like