0% found this document useful (0 votes)
17 views113 pages

Unit 5

This document provides an overview of Java Servlets and Java Server Pages (JSP), detailing their architecture, life cycle, and advantages. It explains the servlet life cycle stages, the role of the servlet container, and how to set up Tomcat as a web server. Additionally, it covers JSP features, scripting elements, and the advantages of using JSP over servlets for dynamic web content creation.

Uploaded by

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

Unit 5

This document provides an overview of Java Servlets and Java Server Pages (JSP), detailing their architecture, life cycle, and advantages. It explains the servlet life cycle stages, the role of the servlet container, and how to set up Tomcat as a web server. Additionally, it covers JSP features, scripting elements, and the advantages of using JSP over servlets for dynamic web content creation.

Uploaded by

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

UNIT 5

Java Servlet

Introduction to Servlets and Hierarchy of Servlets , Life cycle of a


servlet, Tomcat configuration, Handling get and post request (HTTP),
Handling a data from HTML to a servlet, Session tracking – Cookies
and Http Session

Java Server Pages

Simple JSP program, Life cycle of a JSP, Objects, Scripting elements –


Declarations, Expressions, Scriplets, Comments JSP Directives – Page
Directive, include directive, Mixing Scriplets and HTML
Introduction to Java Servlets

• 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:


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

• 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.
The advantages of Servlet are as follows:

1. Better performance: because it creates a thread for


each request, not process.

2. Portability: because it uses Java language.

3. Robust: JVM manages Servlets, so we don't need to


worry about the memory leak, garbage collection, etc.

4. Secure: because it uses java language.


Life Cycle of a Servlet (Servlet Life Cycle)

The web container maintains the life cycle of a servlet


instance. Let's see the life cycle of the servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked
As displayed in the above diagram, there are three states of a
servlet: new, ready and end.

The servlet is in new state if servlet instance is created. After


invoking the init() method, Servlet comes in the ready state.
In the ready state, servlet performs all the tasks. When the web
container invokes the destroy() method, it shifts to the end state.

1) Servlet class is loaded


The classloader is responsible to load the servlet class. The
servlet class is loaded when the first request for the servlet is
received by the web container.

2) Servlet instance is created


The web container creates the instance of a servlet after loading
the servlet class. The servlet instance is created only once in the
servlet life cycle.
3) init method is invoked
The web container calls the init method only once after creating the
servlet instance. The init method is used to initialize the servlet. It is the
life cycle method of the javax.servlet.Servlet interface. Syntax of the
init method is given below:

public void init(ServletConfig config) throws ServletException

4) service method is invoked


The web container calls the service method each time when request for
the servlet is received. If servlet is not initialized, it follows the first
three steps as described above then calls the service method. If servlet is
initialized, it calls the service method. Notice that servlet is initialized
only once. The syntax of the service method of the Servlet interface is
given below:

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException
5) destroy method is invoked

The web container calls the destroy method before


removing the servlet instance from the service. It
gives the servlet an opportunity to clean up any resource
for example memory, thread etc. The syntax
of the destroy method of the Servlet interface is given
below:

public void destroy()


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.
Setting up Web Server − Tomcat

• A number of Web Servers that support servlets are available in the


market. Some web servers are freely downloadable and Tomcat is one
of them.

• Apache Tomcat is an open source software implementation of the


Java Servlet and Java Server Pages technologies and can act as a
standalone server for testing servlets and can be
integrated with the Apache Web Server.

• The following are the steps to setup Tomcat on your machine:

Download latest version of Tomcat from https://tomcat.apache.org/.


• Tomcat can be started by executing the few server
related commands

• After startup, the default web applications included with


Tomcat will be available by visiting
http://localhost:8080/.

• Tomcat can be stopped

• Setting Up the CLASSPATH


Servlet API

The Java Servlet API is a class library for Servlets. Servlets are Java
programs that run on the server and send response to the client. Two
packages are available for Servlet programmers: 1) javax.servlet and 2)
javax.servlet.http.

The first one contains basic classes and interfaces that we can use to write
Servlets from the scratch. The second package, javax.servlet.http, offers
more advanced classes and interfaces that extend classes and interfaces
from the first package. It is much more convenient to program using the
second package.
javax.servlet
Servlet class Hierarchy

• Servlet interface is at the top of the Servlet Hierarchy. It contains


the life cycle methods namely, init (), service () and destroy ().

• It also contains getServletConfig() and getServletInfo() methods.


GenericServlet is an abstract class that implements most of the
basic Servlet methods we will need, including those from the
Servlet interface.

• HttpServlet is also an abstract class that extends the


GenericServlet class. This class implements the service() method
in a HTTP-specific request and response based manner. It also
implements the doGet() and doPost() methods.

• The figure below shows the Servlet hierarchy with important


methods for each of the interface and classes using UML class
diagram:
Advantages of a Java Servlet

• Servlet is faster 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.
HTTP protocol
HTTP is a protocol which allows the fetching of resources,
such as HTML documents. It is the foundation of any data
exchange on the Web and it is a client-server protocol, which
HTTP protocol

HTTP is a protocol which allows the fetching of resources,


such as HTML documents.

It is the foundation of any data exchange on the Web and it is


a client-server protocol, which means requests are initiated by
the recipient, usually the Web browser.

A complete document is reconstructed from the different sub-


documents fetched, for instance text, layout description,
images, videos, scripts, and more.
Clients and servers communicate by exchanging individual messages (as
opposed to a stream of data). The messages sent by the client, usually a
Web browser, are called requests and the messages sent by the server as
an answer are called responses.

Basic Features There are three basic features that make HTTP a simple
but powerful protocol:

HTTP is connectionless: The HTTP client, i.e., a browser initiates an


HTTP request and after a request is made, the client waits for the
response. The server processes the request and sends a response back
after which client disconnect the connection. So client and server knows
about each other during current request and response only. Further
requests are made on new connection like client and server are new to
each other.

HTTP is media independent: It means, any type of data can be sent by


HTTP as long as both the client and the server know how to handle the
data content. It is required for the client as well as the server to specify
the content type using appropriate MIME-type.
HTTP is stateless: As mentioned above, HTTP is connectionless
and it is a direct result of HTTP being a stateless protocol.

The server and client are aware of each other only during a
current request.

Afterwards, both of them forget about each other.

Due to this nature of the protocol, neither the client nor the
browser can retain information between different requests across
the web pages.
HTTP Servlet
If you creating Http Servlet you must extend
javax.servlet.http.HttpServlet class, which is an
abstract class. Unlike Generic Servlet, the HTTP
Servlet doesn’t override the service()
method.
Instead it overrides one or more of the following
methods. It must override at least one method from
the list below:
doGet() – This method is called by servlet service
method to handle the HTTP GET request from
client. The Get method is used for getting
information from the server

doPost() – Used for posting information to the


Server
doPut() – This method is similar to doPost method but unlike
doPost method where we send information to the server, this
method sends file to the server, this is similar to the
FTP operation from client to server

doDelete() – allows a client to delete a document, webpage


or information from the server

init() and destroy() – Used for managing resources that are


held for the life of the servlet

getServletInfo() – Returns information about the servlet, such


as author, version, and copyright.

In Http Servlet there is no need to override the service()


method as this method dispatches the Http Requests to the
correct method handler, for example if it receives HTTP GET
Request it dispatches the request to the doGet() method.
JSP(JavaServer Pages)
JSP(JavaServer Pages)

• JavaServer Pages (JSP) is a technology for developing web pages


that support dynamic content which helps developers insert
java code in HTML pages by making use of special JSP tags.

• Using JSP, you can collect input from users through web page
forms, present records from a database or another source, and
create web pages dynamically.

• JSP vs. Pure Servlets: It is more convenient to write (and to


modify!) regular HTML than to have plenty of println statements
that generate the HTML.
What is JSP?
In Java, JSP stands for Java Server Pages. It is a server-side
technology which is used for creating web applications. It
is used to create dynamic web content. JSP consists of both
HTML tags and JSP tags. In this, JSP tags are used to insert
JAVA code into HTML pages. It is an advanced version of
Servlet Technology i.e. a web-based technology that helps
us to create dynamic and platform-independent web pages.
In this, Java code can be inserted in HTML/ XML pages or
both. JSP is first converted into a servlet by the JSP
container before processing the client’s request. JSP has
various features like JSP Expressions, JSP tags, JSP
Expression Language, etc.
How JSP more advantageous than Servlet?

• They are easy to maintain.

• No recompilation or redeployment is required.

• Less coding is required in JSP.

• JSP has access to the entire API of JAVA.

• JSP are extended version of Servlet.


Features of JSP
• Coding in JSP is easy : As it is just adding JAVA code to
HTML/XML.

• Reduction in the length of Code : In JSP we use action


tags, custom tags etc.

• Connection to Database is easier : It is easier to connect


website to database and allows to read or
write data easily to the database.

• Make Interactive websites : In this we can create dynamic


web pages which helps user to interact
in real time environment.

• Portable, Powerful, flexible and easy to maintain : as


these are browser and server independent.
• No Redeployment and No Re-Compilation : It is dynamic, secure and
platform independent so no need to re-compilation.

• Extension to Servlet : as it has all features of servlets, implicit objects


and custom tags
1. Declaration Tag : It is used to declare variables.
2. Java Scriplets : It allows us to add any number of JAVA code, variables
and expressions.
3. JSP Expression : It evaluates and convert the expression to a string.
4. JAVA Comments : It contains the text that is added for information which
has to be ignored.
• Create html page from where request will be sent to server eg try.html.
• To handle to request of user next is to create .jsp file Eg. new.jsp
• Create project folder structure.
• Create XML file eg my.xml.
• Create WAR file.
• Start Tomcat
• Run Application
Life cycle of a JSP

A JSP life cycle can be defined as the entire process from


its creation till the destruction which is similar to a servlet
life cycle with an additional step which is required to
compile a JSP into servlet.

The following are the paths followed by a JSP

• Compilation
• Initialization
• Execution
• Cleanup
Coding in Servlet
Coding in JSP
How to write a comment in a JSP page?
JSP Scripting elements

The scripting elements provides the ability to insert java code


inside the jsp. There are three types of scripting elements:

1. scriptlet tag

2. expression tag

3. declaration tag
JSP scriptlet tag

A scriptlet tag is used to execute java source code in JSP.


Syntax is as follows:

<% java source code %>

• The statement which is written will be moved to


jspservice() using JSP container while generating servlet
from JSP.

• When client make a request, JSP service method is


invoked and after that the content which is written
inside the scriptlet tag executes.
Example:

<html>
<body>
<% out.print(“Welcome to JSP"); %> <!-- scriptlet tag -->
</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

Declaration tag is one of the scripting elements in JSP.

This Tag is used for declare the variables. Along with this,
Declaration Tag can also declare method and classes.

Jsp initializer scans the code and find the declaration tag
and initializes all the variables, methods, and classes.

Syntax of JSP declaration tag

<%! field or method declaration %>


Mixing Scriptlets and HTML

• We have already seen how to use the "out" variable to generate


HTML output from within a scriptlet. For more complicated
HTML, using the out variable all the time loses some of the
advantages of JSP programming.

• It is simpler to mix scriptlets and HTML.Suppose you have to


generate a table in HTML.

• This is a common operation, and you may want to generate a


table from a SQL table, or from the lines of a file. But to keep
our example simple, we will generate a table containing the
numbers from 1 to N. Not very useful, but it will show you the
technique.

Here is the JSP fragment to do it:


<html>
<body>
<h1> Mixing JSP Scriplet and HTML</h1>
<table width=”100px” border=”2”>
<%
Int I;
For(i=1;i<=10;i++)
{
%>
<tr>
<td><% out.println(i);%></td>
</tr>
<%
}
%>
</table>
</body>
</html>
• The important things to notice are how the %> and <%
characters appear in the middle of the "for" loop, to let you
drop back into HTML and then to come back to the scriptlet.

• The concepts are simple here -- as you can see, you can drop
out of the scriptlets, write normal HTML, and get back into the
scriptlet.

• Any control expressions such as a "while" or a "for" loop or an


"if" expression will control the HTML also. If the HTML is inside
a loop, it will be emitted once for each iteration of the loop.

• It is a little difficult to keep track of all open braces and


scriptlet start and ends
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:

1. page directive
2. include directive
3. taglib directive
Include Directive

• Include directive is used to copy the content of one page to


another. It’s like including the code of one file into another.

• The include directive includes the original content of the


included resource at page translation time (The phase where
JSP gets converted into the equivalent Servlet).

• Why we need to use the include directive?


You may be wondering why we need to use include directive,
can’t we simply add the file’s content in the current JSP instead
of using the directive?
• We can copy the content of external file and paste it in
the main JSP, however it would not be a good
programming practice.

• Let’s understand this with the help of an example – I


have 100 external files and one main JSP file.

• If I just copy the content of all files in the main JSP then I
have to edit it whenever there is a change in any of the
external file, instead we can include all files using
directive and edit the particular file whenever needed.
Also, by using include directive you can enhance the code
re-usability: Let’s say there is a certain code or data which
needs to be there in all the JSP pages of your application
then you can simply have that code/data in one file and
include the file in all the JSP pages.

Syntax of Include Directive


<%@include file ="value"%>

Here, value is the JSP file name which needs to be


included. If the file is in the same directory then just
specify the file name otherwise complete URL(or path)
needs to be mentioned in the value field.
JSP page directive
The page directive defines attributes that apply to
an entire JSP page.

Syntax of JSP page directive


<%@ page attribute="value" %>

Attributes of JSP page directive


• import
• contentType
• extends
• info
• buffer
• language
• isELIgnored
• isThreadSafe
• autoFlush
• session
• pageEncoding
• errorPage
• isErrorPage
2)contentType

The contentType attribute defines the MIME(Multipurpose


Internet Mail Extension) type of the HTTP response.The default
value is "text/html;charset=ISO-8859-1".

You might also like