[go: up one dir, main page]

0% found this document useful (0 votes)
25 views7 pages

Unit V WT

Servlet and JSP

Uploaded by

srnarayanan_slm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views7 pages

Unit V WT

Servlet and JSP

Uploaded by

srnarayanan_slm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

UNIT V- SERVLETS AND JSP

Introduction – Servlet – Architecture – Lifecycle– Generic Servlet & HTTP Servlet - JSP – Overview –
Objects – scripting – Standard Actions – Directives.
Exercise : implement the web applications using (a) Servlets and (b) JSP
--------------------------------------------------------------------------------------------------------------------
Introduction – Servlet
Servlets are the Java programs that run on the Java-enabled web server or application server.
They are used to handle the request obtained from the webserver, process the request, produce the
response, then send a response back to the webserver.

Properties of Servlets are as follows:


 Servlets work on the server-side.
 Servlets are capable of handling complex requests obtained from the webserver.

Advantages of a Java Servlet


 Servlet is faster than CGI as it doesn’t involve the creation of a new process for every new
request received.
 Servlets, as written in Java, are platform-independent.
 Removes the overhead of creating a new process for each request as Servlet doesn’t run in a
separate process. There is only a single instance that handles all requests concurrently. This also
saves the memory and allows a Servlet to easily manage the client state.
 It is a server-side component, so Servlet inherits the security provided by the Web server.
 The API designed for Java Servlet automatically acquires the advantages of the Java platforms
such as platform-independent and portability. In addition, it obviously can use the wide range of
APIs created on Java platforms such as JDBC to access the database.
 Many Web servers that are suitable for personal use or low-traffic websites are offered for free
or at extremely cheap costs eg. Java servlet. However, the majority of commercial-grade Web
servers are rather expensive, with the notable exception of Apache, which is free.

The Servlet Container


Servlet container, also known as Servlet engine is an integrated set of objects that provide a run
time environment for Java Servlet components.
In simple words, it is a system that manages Java Servlet components on top of the Web server to
handle the Web client requests.
Services provided by the Servlet container :
 Network Services: Loads a Servlet class. The loading may be from a local file system, a remote
file system or other network services. The Servlet container provides the network services over
which the request and response are sent.
 Decode and Encode MIME-based messages: Provides the service of decoding and encoding
MIME-based messages.
 Manage Servlet container: Manages the lifecycle of a Servlet.
 Resource management Manages the static and dynamic resources, such as HTML files,
Servlets, and JSP pages.
 Security Service: Handles authorization and authentication of resource access.
 Session Management: Maintains a session by appending a session ID to the URL path.
Architecture
Servlet Architecture is can be depicted from the image itself as provided below as follows:

Execution of Servlets basically involves six basic steps:


1. The clients send the request to the webserver.
2. The web server receives the request.
3. The web server passes the request to the corresponding servlet.
4. The servlet processes the request and generates the response in the form of output.
5. The servlet sends the response back to the webserver.
6. The web server sends the response back to the client and the client browser displays it on the
screen.

Lifecycle
The entire life cycle of a Servlet is managed by the Servlet container which uses
the javax.servlet.Servlet interface to understand the Servlet object and manage it. So, before
creating a Servlet object, let’s first understand the life cycle of the Servlet object which is actually
understanding how the Servlet container manages the Servlet object.

Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes through four stages,
 Loading a Servlet.
 Initializing the Servlet.
 Request handling.
 Destroying the Servlet.
Let’s look at each of these stages in details:
1. Loading a Servlet: The first stage of the Servlet lifecycle involves loading and initializing the
Servlet by the Servlet container. The Web container or Servlet Container can load the Servlet at
either of the following two stages :
 Initializing the context, on configuring the Servlet with a zero or positive integer value.
 If the Servlet is not preceding stage, it may delay the loading process until the Web
container determines that this Servlet is needed to service a request.
2. Initializing a Servlet: After the Servlet is instantiated successfully, the Servlet container
initializes the instantiated Servlet object. The container initializes the Servlet object by
invoking the Servlet.init(ServletConfig) method which accepts ServletConfig object
reference as parameter.
The Servlet container invokes the Servlet.init(ServletConfig) method only once,
immediately after the Servlet.init(ServletConfig) object is instantiated successfully. This
method is used to initialize the resources, such as JDBC datasource. Now, if the Servlet fails to
initialize, then it informs the Servlet container by throwing
the ServletException or UnavailableException.
3. Handling request: After initialization, the Servlet instance is ready to serve the client
requests. The Servlet container performs the following operations when the Servlet instance
is located to service a request :
4. Destroying a Servlet: When a Servlet container decides to destroy the Servlet, it performs the
following operations,
 It allows all the threads currently running in the service method of the Servlet instance to
complete their jobs and get released.
 After currently running threads have completed their jobs, the Servlet container calls
the destroy() method on the Servlet instance.
After the destroy() method is executed, the Servlet container releases all the references of this
Servlet instance so that it becomes eligible for garbage collection.

Generic Servlet & HTTP Servlet


GenericServlet and HttpServlet Comparison Chart

JSP Overview
Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
platform-independent method for building Web-based applications. JSP have access to the entire family
of Java APIs, including the JDBC API to access enterprise databases.
JavaServer Pages often serve the same purpose as programs implemented using the Common Gateway
Interface (CGI). But JSP offers several advantages in comparison with the CGI.
 Performance is significantly better because JSP allows embedding Dynamic Elements in HTML
Pages itself instead of having separate CGI files.
 JSP are always compiled before they are processed by the server unlike CGI/Perl which requires
the server to load an interpreter and the target script each time the page is requested.
 JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access
to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP, etc.
 JSP pages can be used in combination with servlets that handle the business logic, the model
supported by Java servlet template engines.
JSP Objects
These Objects are the Java objects that the JSP Container makes available to the developers in
each page and the developer can call them directly without being explicitly declared. JSP Implicit
Objects are also called pre-defined variables.
Following table lists out the nine Implicit Objects that JSP supports –

S.No. Object & Description

request
1
This is the HttpServletRequest object associated with the request.

response
2
This is the HttpServletResponse object associated with the response to the client.

out
3
This is the PrintWriter object used to send output to the client.

session
4
This is the HttpSession object associated with the request.

application
5
This is the ServletContext object associated with the application context.

config
6
This is the ServletConfig object associated with the page.

pageContext
7
This encapsulates use of server-specific features like higher performance JspWriters.

page
8 This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.

Exception
9
The Exception object allows the exception data to be accessed by designated JSP.

JSP Scripting
In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what are the
scripting elements first.

JSP Scripting elements


The scripting elements provides the ability to insert java code inside the jsp. There are three types of
scripting elements:
o scriptlet tag
o expression tag
o declaration tag

JSP scriptlet tag


A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
<% java source code %>
Example:
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>

JSP expression tag


The code placed within JSP expression tag is written to the output stream of the response. So you
need not write out.print() to write data. It is mainly used to print the values of variable or method.

Syntax of JSP expression tag


<%= statement %>

Example of JSP expression tag


In this example of jsp expression tag, we are simply displaying a welcome message.
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>

JSP Declaration Tag


The JSP declaration tag is used to declare fields and methods.
The code written inside the jsp declaration tag is placed outside the service() method of auto generated
servlet.
So it doesn't get memory at each request.

Syntax of JSP declaration tag


The syntax of the declaration tag is as follows:
<%! field or method declaration %>

Example of JSP declaration tag that declares field


In this example of JSP declaration tag, we are declaring the field and printing the value of the declared
field using the jsp expression tag.
index.jsp
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>

Standard Actions
These actions use constructs in XML syntax to control the behavior of the servlet engine. You
can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or
generate HTML for the Java plugin.

There is only one syntax for the Action element, as it conforms to the XML standard −
<jsp:action_name attribute = "value" />
Action elements are basically predefined functions.
The following table lists out the available JSP actions −
S.No. Syntax & Purpose

jsp:include
1
Includes a file at the time the page is requested.

jsp:useBean
2
Finds or instantiates a JavaBean.

jsp:setProperty
3
Sets the property of a JavaBean.

jsp:getProperty
4
Inserts the property of a JavaBean into the output.

jsp:forward
5
Forwards the requester to a new page.

jsp:plugin
6 Generates browser-specific code that makes an OBJECT or EMBED tag for the Java
plugin.

jsp:element
7
Defines XML elements dynamically.

jsp:attribute
8
Defines dynamically-defined XML element's attribute.

jsp:body
9
Defines dynamically-defined XML element's body.

jsp:text
10
Used to write template text in JSP pages and documents.

JSP Directives.
The jsp directives are messages that tells the web container how to translate a JSP page into the
corresponding servlet.
There are three types of directives:
o page directive
o include directive
o taglib directive
Syntax of JSP Directive
<%@ directive attribute="value" %>

JSP page directive


The page directive defines attributes that apply to an entire JSP page.
Syntax of JSP page directive
<%@ page attribute="value" %>
Example:
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>

Jsp Include Directive


The include directive is used to include the contents of any resource it may be jsp file, html file or text
file. The include directive includes the original content of the included resource at page translation
time (the jsp page is translated only once so it will be better to include static resource).

Advantage of Include directive


Code Reusability

Syntax of include directive


<%@ include file="resourceName" %>

Example:
<html>
<body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>

JSP Taglib directive


The JSP taglib directive is used to define a tag library that defines many tags. We use the TLD (Tag
Library Descriptor) file to define the tags. In the custom tag section we will use this tag so it will be
better to learn it in custom tag.

Syntax JSP Taglib directive


<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>

Example:
<html>
<body>
<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
<mytag:currentDate/>
</body>
</html>

You might also like