0% found this document useful (0 votes)
6 views

web tech unit 5

Uploaded by

springboot513
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

web tech unit 5

Uploaded by

springboot513
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Unit 5

What are Servlets?


Java Servlets are programs that run on a Web or Application server and act as a middle layer
between requests coming from a Web browser or other HTTP client and databases or
applications on the HTTP server.

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

Servlets Architecture:
The following diagram shows the position of Servlets in a Web Application.

1. Client

The client shown in the architecture above is the web browser and it primarily works as a
medium that sends out HTTP requests over to the web server and the web server generates a
response based on some processing in the servlet and the client further processes the response.

2. Web Server

Primary job of a web server is to process the requests and responses that a user sends over time
and maintain how a web user would be able to access the files that has been hosted over the
server. The server we are talking about here is a software which manages access to a centralized
resource or service in a network. There are precisely two types of webservers:
● Static web server
● Dynamic web server

3. Web Container

Web container is another typical component in servlet architecture which is responsible for
communicating with the servlets. Two prime tasks of a web container are:
● Managing the servlet lifecycle
● URL mapping

Web container sits at the server-side managing and handling all the requests that are coming in
either from the servlets or from some JSP pages or potentially any other file system.

Life Cycle of a Servlet:

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.:
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. The Servlet container performs two operations in this stage :
● Loading : Loads the Servlet class.
● Instantiation : Creates an instance of the Servlet. To create a new
instance of the Servlet, the container uses the no-argument constructor.

3.
4. 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.
5. 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 :
● It creates the ServletRequest and ServletResponse objects. In this case, if
this is a HTTP request, then the Web container creates
HttpServletRequest and HttpServletResponse objects which are
subtypes of the ServletRequest and ServletResponse objects
respectively.
● After creating the request and response objects it invokes the
Servlet.service(ServletRequest, ServletResponse) method by passing the
request and response objects.
6. The service() method while processing the request may throw the ServletException

or UnavailableException or IOException.
7. 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.

HTTP Requests
The request sent by the computer to a web server, contains all sorts of potentially interesting
information; it is known as HTTP requests.

The HTTP client sends the request to the server in the form of request message which includes
following information:

○ The Request-line
○ The analysis of source IP address, proxy and port
○ The analysis of destination IP address, protocol, port and host
○ The Requested URI (Uniform Resource Identifier)
○ The Request method and Content
○ The User-Agent header
○ The Connection control header
○ The Cache control header
The HTTP request method indicates the method to be performed on the resource identified by t

The Requested URI (Uniform Resource Identifier). This method is case-sensitive and should be
used in uppercase.

HTTP Request Description

1.GET Asks to get the resource at the requested


URL.

2. POST Asks the server to accept the body info


attached. It is like GET request with extra
info sent with the request.

3. HEAD Asks for only the header part of whatever a


GET would return. Just like GET but with no
body.

4. TRACE Asks for the loopback of the request message,


for testing or troubleshooting.
5. PUT Says to put the enclosed info (the body) at the
requested URL.

6. DELETE Says to delete the resource at the requested


URL.

7. OPTIONS Asks for a list of the HTTP methods to which


the thing at the request URL can respond

SendRedirect in servlet:
1. sendRedirect method
2. Syntax of sendRedirect() method
3. Example of RequestDispatcher interface

The sendRedirect() method of HttpServletResponse interface can be used to redirect response to


another resource, it may be a servlet, jsp or html file.

It accepts relative as well as absolute URL.

It works at client side because it uses the url bar of the browser to make another request. So, it
can work inside and outside the server.

Session Tracking in Servlets:


1. Session Tracking
2. Session Tracking Techniques

Session simply means a particular interval of time.

Session Tracking is a way to maintain state (data) of a user. It is also known as session
management in servlet.

Http protocol is stateless so we need to maintain state using session tracking techniques. Each
time a user requests to the server, the server treats the request as the new request. So we need to
maintain the state of a user to recognize a particular user.

HTTP is stateless, which means each request is considered as the new request. It is shown in the
figure given below:
Why use Session Tracking?
To recognize the user It is used to recognize the particular user.

Session Tracking Techniques:


There are four techniques used in Session tracking:

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

HTTP cookie:
HTTP cookies (also called web cookies, Internet cookies, browser cookies, or simply cookies)
are small blocks of data created by a web server while a user is browsing a website and placed on
the user's computer or other device by the user's web browser. Cookies are placed on the device
used to access a website, and more than one cookie may be placed on a user's device during a
session.

Cookies serve useful and sometimes essential functions on the web. They enable web servers to
store stateful information (such as items added in the shopping cart in an online store) on the
user's device or to track the user's browsing activity (including clicking particular buttons,
logging in, or recording which pages were visited in the past).[1] They can also be used to save
information that the user previously entered into form fields, such as names, addresses,
passwords, and payment card numbers for subsequent use.
HttpSession interface:
1. HttpSession interface
2. How to get the HttpSession object
3. Commonly used methods of HttpSession interface
4. Example of using HttpSession

In such case, container creates a session id for each user.The container uses this id to identify the
particular user.An object of HttpSession can be used to perform two tasks:

1. bind objects
2. view and manipulate information about a session, such as the session identifier, creation
time, and last accessed time.

How to get the HttpSession object ?


The HttpServletRequest interface provides two methods to get the object of HttpSession:

1. public HttpSession getSession():Returns the current session associated with this request,
or if the request does not have a session, creates one.
2. public HttpSession getSession(boolean create):Returns the current HttpSession associated
with this request or, if there is no current session and create is true, returns a new session.

Commonly used methods of HttpSession interface:


1. public String getId():Returns a string containing the unique identifier value.
2. public long getCreationTime():Returns the time when this session was created, measured
in milliseconds since midnight January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the client sent a request
associated with this session, as the number of milliseconds since midnight January 1,
1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects bound to it.

Introduction to JSP:
In Java, JSP stands for Jakarta Server Pages( (JSP; formerly JavaServer Pages)). It is a
server-side technology that 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.
JSP allows embedding Java code in HTML pages, making it easier to build interactive web
applications. To further enhance your knowledge of Java web technologies, consider enrolling in
the Java Backend course, which covers essential concepts for backend development.
How is 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 is an extended version of Servlet.

What are Java Server Pages?


JavaServer Pages (JSP) is a technology for developing Web Pages that supports dynamic content.
This helps developers insert java code in HTML pages by making use of special JSP tags, most
of which start with <% and end with %>.

A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a
user interface for a Java web application. Web developers write JSPs as text files that combine
HTML or XHTML code, XML elements, and embedded JSP actions and commands.
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.

Why Use JSP?


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.

​ Example of a JSP Web Page:


​ <HTML>
​ <HEAD>
​ <TITLE>A Web Page</TITLE>
​ </HEAD>
​ <BODY>
​ <%out.println("Hello there!");%>
​ </BODY>
​ </HTML>

Implicit Objects – request and response:


request Object:
The JSP request is an implicit object which is provided by HttpServletRequest. In the servlet, we
have to first import javax.servlet.http.HttpServletRequest then we have to create its object for
taking input from any HTML form as.

Syntax :
import javax.servlet.http.HttpServletRequest;

public class LoginServlet extends HttpServlet


{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
HttpSession session = request.getSession()
}
}

response object:

This is the HttpServletResponse object associated with the response to the client. The response
object also defines the interfaces that deal with creating new HTTP headers. Through this object
the JSP programmer can add new cookies or date stamps, HTTP status codes, etc.

JSP Scriptlet tag (Scripting elements):


1. Scripting elements
2. JSP scriptlet tag
3. Simple Example of JSP scriptlet tag
4. Example of JSP scriptlet tag that prints the user name

In JSP, java code can be written inside the jsp page using the scriptlet tag.

JSP Scripting elements:

The scripting element provides the ability to insert java code inside the jsp. There are three types
of scripting elements:

○ scriptlet tag
○ expression tag
○ 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 of JSP scriptlet tag:


In this example, we are displaying a welcome message.

​ <html>
​ <body>
​ <% out.print("welcome to jsp"); %>
​ </body>
​ </html>

JSP Action Tags:


1. JSP Action Tags
2. jsp:forward action tag
3. Example of jsp:forward action tag without parameter
4. Example of jsp:forward action tag with parameter

There are many JSP action tags or elements. Each JSP action tag is used to perform some
specific tasks.

The action tags are used to control the flow between pages and to use Java Bean. The Jsp action
tags are given below.
JSP Action Tags Description

jsp:forward forwards the request and response to another


resource.

jsp:include includes another resource.

jsp:useBean creates or locates bean object.

jsp:setProperty sets the value of property in bean object.

jsp:getProperty prints the value of property of the bean.

jsp:plugin embeds another components such as applet.

jsp:param sets the parameter value. It is used in forward


and include mostly.

jsp:fallback can be used to print the message if plugin is


working. It is used in jsp:plugin.

JSP directives:
1. JSP directives
1. page directive
2. Attributes of page directive
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:

● page directive
● include directive
● 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" %>

Attributes of JSP page directive


○ import
○ contentType
○ extends
○ info
○ buffer
○ language
○ isELIgnored
○ isThreadSafe
○ autoFlush
○ session
○ pageEncoding
○ errorPage
Custom Tags in JSP:
Custom tags are user-defined action tags that can be used within Java Server Pages. A tag
handler is associated with each tag to implement the operations. Therefore, it separates the
business logic from JSP and helps avoid the use of scriptlet tags. The scriptlet tag embeds java
code inside the JSP page itself rendering the page difficult to understand therefore, it is better to
avoid the use of scriptlet.
Reasons to avoid scriptlets in JSP:
Both scriptlets and custom tags use servlets at the core, therefore, they do not differ much in
performance. But custom tags are always preferred over scriptlets for the following reasons :
● Custom tags separate the business logic from Java Server Pages. JSP still controls the
flow but processing is delegated to a separate java class( tag handler class).
● It increases the readability of Java Server Pages. Scriptless JSPs are a lot easier to
read and understand as compared to JSPs embedded with scriptlets.
● It is easier for a frontend developer to use tags rather than writing java code inside the
JSPs.
● Custom tags can be reused across various applications but it is not possible to reuse
the java code embedded within a JSP using scriptlets.

You might also like