WEB - M4
WEB - M4
WEB - M4
Introduction to Servlets
By,
Dr. Raviprakash M L
Professor
Dept. of CSE
KIT, Tiptur
Contents
Servlets are capable of handling complex requests obtained from the web server.
Execution of Servlets basically involves Six basic steps:
• The Servlet processes the request and generates the response in the form of
output.
• The Web Server sends the response back to the client and the client browser
displays it on the screen.
CGI (Common gateway interface)
CGI was the first protocol or way of communication between web server and
program. It passes a request from a web user to an application program and receives
data back to forward to the web user i.e. It is responsible for dynamic content
generation.
Advantages of CGI:
• Technology portability: CGI programming can be written in variety of languages
like c, c++, perl.
• Web server portability: All service providers support CGI Programs.
Disadvantages:
• Response time is high.
• CGI scripts are platform-dependent.
• For every request, a new process will be started
• and web server is limited to start processes.
• CGI programs are not object oriented always.
Difference between Java Servlets and CGI
Servlets can directly communicate with the CGI cannot directly communicate with the
webserver. webserver.
Servlets are less expensive than CGI. CGI is more expensive than Servlets.
Servlets can handle the cookies. CGI cannot handle the cookies.
Servlets - Life Cycle
1. Create the servlet class: This class typically extends javax.servlet.http.HttpServlet and
overrides methods like doGet and doPost to handle HTTP requests.
2. Package the servlet: Along with the servlet class, you might have other helper classes or
resources. These are often packaged into a JAR file.
4. Package the web application: The servlet class (JAR), deployment descriptor (web.xml), and
any other web resources (like HTML, CSS) are bundled together into a WAR (Web ARchive)
file.
5. Deploy to the server: The WAR file is copied to a specific location on the web server or
application server. The server detects the WAR and deploys the web application.
Servlet API
In Java, to create web applications we use Servlets. To create Java Servlets, we need to use Servlet
API which contains all the necessary interfaces and classes. Servlet API has 2 packages namely,
1. javax.servlet
2. javax.servlet.http
The javax.servlet package contains many interfaces and classes that are used by the servlet or web
container. These are not specific to any protocol.
These interfaces and classes describe and define the contracts between a servlet class and the runtime
environment provided by a servlet container.
The javax.servlet.http package contains interfaces and classes that are responsible for http requests
only.
These interfaces and classes describe and define the contracts between a servlet class running under
HTTP protocol and the runtime environment provided by a servlet container.
Classes available in javax.servlet package:
Class Name Description
To generate notifications about changes to the attributes of the servlet context of a web
ServletContextAttributeEvent
application.
ServletContextEvent To generate notifications about changes to the servlet context of a web application.
ServletInputStream This class provides an input stream to read binary data from a client request.
ServletOutputStream This class provides an output stream for sending binary data to the client.
This class provides the implementation of the ServletRequest interface that can be subclassed
ServletRequestWrapper
by developers to adapt the request to a Servlet.
This class provides the implementation of the ServletResponse interface that can be
ServletResponseWrapper
subclassed by developers to adapt the response from a Servlet.
Interfaces in javax.servlet package
Interface Name Description
Filter To perform filtering tasks on either the request to a resource, or on the response from a resource, or both.
FilterChain To provide a view into the invocation chain of a filtered request for a resource to the developer by the servlet container.
It defines an object to dispatch the request and response to any other resource, means it receives requests from the client and sends them to a
RequestDispatcher
servlet/HTML file/JSP file on the server.
This is the main interface that defines the methods in which all the servlets must implement. To implement this interface, write a generic servlet
Servlet
that extends javax.servlet.GenericServlet or an HTTP servlet that extends javax.servlet.http.HttpServlet.
ServletConfig It defines an object created by a servlet container at the time of servlet instantiation and to pass information to the servlet during initialization.
It defines a set of methods that a servlet uses to communicate with its servlet container. The information related to the web application available in
ServletContext
web.xml file is stored in ServletContext object created by container.
ServletContextAttributeListener The classes that implement this interface receive notifications of changes to the attribute list on the servlet context of a web application.
ServletContextListener The classes that implement this interface receive notifications about changes to the servlet context of the web application they are part of.
ServletRequest It defines an object that is created by servlet container to pass client request information to a servlet.
To generate the notifications of request attribute changes while the request is within the scope of the web application in which the listener is
ServletRequestAttributeListener
registered.
ServletRequestListener To generate the notifications of requests coming in and out of scope in a web component.
ServletResponse It defines an object created by servlet container to assist a servlet in sending a response to the client.
Classes available in javax.servlet.http package:
Class Name Description
Creates a cookie object. It is a small amount of information sent by a servlet to a Web browser,
Cookie
saved by the browser, and later sent back to the server used for session management.
Provides an abstract class that defines methods to create an HTTP suitable servlet for a web
HttpServlet
application.
This class provides implementation of the HttpServletRequest interface that can be subclassed
HttpServletRequestWrapper
to adapt the request to a Servlet.
This events are either sent to an object that implements HttpSessionBindingListener when it is
bound or unbound from a session, or to a HttpSessionAttributeListener that has been
HttpSessionBindingEvent
configured in the deployment descriptor when any attribute is bound, unbound or replaced in
a session.
HttpSessionEvent To represent event notifications for changes to sessions within a web application.
Interfaces available in javax.servlet.http package:
Interface Name Description
HttpServletRequest To provide client HTTP request information for servlets. It extends the ServletRequest interface.
It provides a way to identify a user across web application/web site pages and to store information
HttpSession
about that user.
Container to notify all the objects that are bound to a session that sessions will be passivated and
HttpSessionActivationListener
that session will be activated.
To get notifications of changes to the attribute lists of sessions within this web application, this
HttpSessionAttributeListener
listener interface can be implemented.
To receive notification events related to the changes to the list of active sessions in a web
HttpSessionListener
application.
Reading Servlets parameters
Servlets parse the form(client) data automatically using the following methods depending on the
situation
• getParameter() − You call request.getParameter() method to get the value of a form parameter.
• getParameterValues() − Call this method if the parameter appears more than once and returns
multiple values, for example checkbox.
• getParameterNames() − Call this method if you want a complete list of all parameters in the
current request
Client pass some information from browser to web server uses GET Method or POST Method.
If a client send the data to the servlet, that data will be available in the object of HttpServletRequest
interface. In case of getParameter() method we have to pass input parameter name and it will give
the value.
Enumeration en=request.getParameterNames();
Syntax: request.getParameter("name")
while(en.hasMoreElements())
{
String param_name = (String) en.nextElement();
String value=request.getParameter(param_name);
.......
}
Reading Initialization Parameters in Servlet
Both ServletContext and ServletConfig are basically the configuration objects which are used by the servlet
container to initialize the various parameter of a web application. But they have some difference in terms of
scope and availability.
Difference between ServletConfig vs. ServletContext
ServletConfig ServletContext
ServletConfig object is one per servlet class. ServletContext object is global to the entire web application.
Object of ServletConfig will be created during the initialization process Object of ServletContext will be created at the time of web application
of the servlet. deployment
We have to give the request explicitly in order to create the ServletConfig ServletContext object can be available even before giving the first
object for the first time. request.
Scope: As long as a servlet is executing, the ServletConfig object will be Scope: As long as a web application is executing, the ServletContext
available, it will be destroyed once the servlet execution is completed. object will be available, and it will be destroyed once the application is
removed from the server.
ServletConfig object is used while only one servlet requires information ServletContext object is used while application requires information
shared by it. shared by it.
getServletConfig() method is used to obtain Servletconfig object. getServletContext() method is used to obtain ServletContext object.
In web.xml — tag will be appear under tag. In web.xml — tag will be appear under tag.
ServletConfig
An object of ServletConfig is created by the web container for each servlet. This object can be used to
get configuration information from web.xml file. If the configuration information is modified from the
web.xml file, we don't need to change the servlet. So it is easier to manage the web application if any
specific content is modified from time to time.
public String getInitParameter(String name): Returns the parameter value for the specified parameter
name.
public Enumeration getInitParameterNames(): Returns an enumeration of all the initialization
parameter names.
public String getServletName(): Returns the name of the servlet
ServletContext
ServletContext object can be used to get configuration information from web.xml
file. There is only one ServletContext object per web application. If any information
is shared to many servlet, it is better to provide it from the web.xml file using the
element.
• Cookies and Sessions are used to store information. Cookies are only
stored on the client-side machine, while sessions get stored on the
client as well as the server.
What is a Cookie?
• Cookies are little text-based files that are kept on the user's computer and are accessible
only by that user's browser. It is possible for a cookie's size to reach a maximum of 4 KB.
• Cookies are also referred to as HTTP cookies, online cookies, and internet cookies,
amongst other names.
• When a person signs into a website or application for the very first time, that website
transmits a large amount of information to the user's computer in the form of cookies.
• When a user opens a site, these cookies maintain track of all of the activities and surfing
they do on the site. The information is saved using the string type.
• The information that is gathered by cookies is not considered to be secure because the
information is kept in texts that are simple to read and understand.
• The users have the ability to control whether the cookies are enabled or disabled
at any time they see fit. Only the user who initially created a cookie has access to
the cookie's information; no other users can see it.
• Cookies are created with the help of an HTTP header and then transferred
between the browser and the server. Cookies are saved in the Temporal Internet
File Folder by Internet Explorer, but the location where they are saved is
determined by the browser being used.
• Cookies read the data that is generated when we search for and play certain songs
on YouTube. Then, the next time that we open YouTube, the same songs or
recommendations that are similar to them are displayed.
Why Use Cookies?
• This period of time begins when the user accesses any website or program and continues until the user exits
the application or shuts down the computer.
• Because the HTTP protocol does not keep track of the user's status, the web server does not recognize the
user as they are navigating the apps available on the internet. The information that the user enters into the
program on the home page or any other page will not be moved to any other pages in the application.
• Sessions are what are used to remove this limitation from the game. Session variables, which can be of any
sort, are where the user's data can be saved if they are chosen to do so.
• The data that is stored by session variables is either encrypted or converted to a binary form on the server,
which protects the data from being accessed by a third party.
• When the user of the application logs out of that application or closes down their computer, the
session value is automatically detached. It is necessary for the session values to be saved in the
database if they are to be retained for a longer period of time.
• Every single session is unique to the individual user, and there is no limit to the number of
sessions that can be used within a single application because there are no constraints placed on it.
• A user can be recognized with the assistance of a session, which is a one-of-a-kind number that is
kept on the server in the form of a cookie, a form field, or a URL.
• The Session ID, which is a one-of-a-kind number that is temporarily stored on the server, is what
is used to identify the user. It is either a cookie, a form field, or a URL that is saved.
Why Use Sessions?
• Sessions are used to store information such as User ID over the server more
securely, where it cannot be altered. This prevents the information from
being tampered with.
• In addition to this, sessions can transfer the information from one web page
to another in the form of value.
• Sessions can be used as a substitute for cookies in web browsers that do not
support cookies, allowing for the storage of variables in a manner that is
more impenetrable.
Comparison between Cookie and Session
The following table highlights the major differences between a cookie and a session
Basis of Comparison Cookie Session
Cookies are client-side files that are stored on a local Sessions are server-side files that store user information.
Definition computer and contain user information.
Cookies expire after the user specified lifetime. The session ends when the user closes the browser or
Expiry logs out of the program.
Data storage It can only store a limited amount of data. It is able to store an unlimited amount of information.
Cookies can only store up to a maximum of 4 KB of There is a maximum memory restriction of 128
data in a browser. megabytes that a script may consume at one time.
Capacity However, we are free to maintain as much data as we like
within a session.
It is not necessary for us to execute a function in order Utilizing the session start()method is required before we
to get cookies going because they are stored on the local can begin the session.
Function
computer.
Data Format Cookies are used to store information in a text file. The data is saved in an encrypted format during sessions.
Storage Cookies are stored on a limited amount of data. A session can store an unlimited amount of data.
Connecting to a database using JDBC
Connecting to a database using JDBC in Java involves a series of steps:
• Import JDBC Packages: Your program needs to import the relevant JDBC packages to interact
with the database. This typically includes java.sql classes like Connection, Statement, and
ResultSet.
• Register JDBC Driver: The JDBC driver acts as a bridge between your Java application and the
specific database you're connecting to. You need to register the appropriate driver class for your
database (e.g., MySQLDriver, OracleDriver) using methods like
Class.forName("driverClassName").
• Establish a Database Connection: Once the driver is registered, you can create a connection to
the database using the DriverManager class. The getConnection method of DriverManager takes
the database URL, username, and password as arguments. The URL specifies the database type,
location, and database name (e.g., jdbc:mysql://localhost:3306/mydatabase).
• Create a Statement Object: A Statement object allows you to execute SQL queries on the
database. You can use the createStatement method of the Connection object to create a Statement
instance.
• Execute SQL Query: Use the execute or specific methods like executeQuery (for SELECT
queries) on the Statement object to execute your desired SQL query.
• Process Results (if applicable): For queries that retrieve data (like SELECT), the executeQuery
method returns a ResultSet object containing the results. You can iterate through the ResultSet to
access each row and column values.
• Close Resources: It's important to close the ResultSet, Statement, and Connection objects after
you're done to release resources and avoid database connection leaks. You can use the close
method on each object to close them.
Thank You