SlideShare a Scribd company logo
HTTP Server Programming
HTTP Fundamentals
 Introduction to HTTP
 HTTP (Hypertext Transfer Protocol) is the foundation of data
communication on the World Wide Web.
 It is a request-response protocol used by web browsers and web
servers to exchange data and information.
 HTTP Request and Response
 An HTTP request is made by a client (usually a web browser) to
request resources from a web server.
 An HTTP response is sent by the server to fulfill the client's request.
 HTTP Methods
 HTTP requests use methods like GET, POST, PUT, DELETE to
define the type of request.
 GET is used to retrieve data, POST to send data to be processed,
PUT to update data, and DELETE to remove data.
Servlet Programming
 Introduction to Servlets
 A servlet is a Java-based technology for building web
applications.
 Servlets run on the server-side and handle client requests and
generate dynamic responses.
 Servlet API
 The Java Servlet API provides a framework for developing
servlets.
 It includes classes and interfaces for handling servlet requests
and responses.
 Creating a Servlet
 To create a servlet, you need to extend the
javax.servlet.http.HttpServlet class and override its doGet or
doPost method.
EXAMPLE
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet logic here
}
}
Web Deployment Descriptor (web.xml)
 The web.xml file is an XML configuration file that maps
URLs to servlets.
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.example.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/myservlet</url-pattern>
</servlet-mapping>
The Life Cycle of a
Servlet; Using Tomcat for Servlet Development
 Initialization
 When a servlet is first loaded, its init method is called.
 You can perform one-time initialization tasks in this method.
 Request Handling
 For each client request, the servlet's service method is called.
 The service method dispatches the request to the appropriate HTTP
method (doGet, doPost, etc.).
 Destruction
 When the servlet container decides to unload the servlet, the destroy
method is called.
 You can perform cleanup tasks in this method.
 Request and Response Objects
 Servlets receive two important objects: HttpServletRequest for the request
and HttpServletResponse for the response.
 You can use these objects to access client data and send responses.
Using Tomcat for Servlet Development
 Apache Tomcat
 Apache Tomcat is an open-source web server and servlet container.
 It is widely used for running Java-based web applications, including servlets.
 Setting up Tomcat
 Download and install Tomcat from the Apache Tomcat website.
 Configure your web application by placing servlet classes and the web.xml file in the
appropriate directories.
 Start Tomcat and deploy your web application.
 Accessing Servlets
 Servlets are accessed using a URL that maps to their URL pattern defined in
web.xml.
 For example, if a servlet is mapped to /myservlet, you can access it at
http://localhost:8080/yourapp/myservlet.
 Tomcat Manager
 Tomcat provides a web-based manager application that allows you to deploy,
undeploy, and manage your web applications.
 You can access it at http://localhost:8080/manager/html.
Servlets - Examples
 Servlets are Java classes which service HTTP
requests and implement
the javax.servlet.Servlet interface.
 Web application developers typically write servlets
that extend javax.servlet.http.HttpServlet, an
abstract class that implements the Servlet interface
and is specially designed to handle HTTP requests.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException {
// Do required initialization
message = "Hello World";
} public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
} public void destroy() { // do nothing. }
}
Servlet Deployment
 By default, a servlet application is located at the path
<Tomcat-installationdirectory>/webapps/ROOT and the
class file would reside in <Tomcat-
installationdirectory>/webapps/ROOT/WEB-
INF/classes.
 If you have a fully qualified class name
of com.myorg.MyServlet, then this servlet class must
be located in WEB-
INF/classes/com/myorg/MyServlet.class.
 For now, let us copy HelloWorld.class into <Tomcat-
installationdirectory>/webapps/ROOT/WEB-
INF/classes and create following entries in web.xml file
located in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/
CONTD
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
 Above entries to be created inside <web-app>...</web-
app> tags available in web.xml file. There could be
various entries in this table already available, but never
mind.
 You are almost done, now let us start tomcat server using
<Tomcat-installationdirectory>binstartup.bat (on
Windows) or <Tomcat-
installationdirectory>/bin/startup.sh (on Linux/Solaris
etc.) and finally
type http://localhost:8080/HelloWorld in the
browser's address box. If everything goes fine, you would
get the following result
Http Server Programming in JAVA - Handling http requests and responses
The Javax.servlet Package
 The Java Servlet API is an acronym for Application
Programming Interface (API) that is used on a server
to interact with the other pages.
 It communicates with the clients through a request
and response format or system in a servlet container.
An application programming interface (API) for
servlets is a group of predefined packages, classes,
and interfaces that have been written, along with
their servlet methods and constructors.
 It is a mechanism for interaction between two web
application components and servlet functions.
What is Servlet API?
 Servlets are Java pieces of code on a web server or server-side that
can handle Java.
 We can manage the request from the remote server, process and
operate the servlet request, make the servlet response, and then
return the web page or server.
 We can also use Servlets to make several web or Java-based
applications. It must utilize the Servlet API, which includes all
virtual interfaces and classes, to make Java Servlets.
 Servlet API comes in two packages, which are:
 javax.servlet
 javax.servlet.http
 The servlet pages or web container uses many interfaces and classes
from the “javax.servlet” package. The “javax.servlet.http” package
has classes and interfaces that manage http requests.
Classes available in javax.servlet package
Classes Description
GenericServlet Defines a generic, protocol-independent
servlet.
ServletInputStream Provides an input stream for reading
binary data from a client request,
including an efficient readLine method
for reading data one line at a time.
ServletOutputStream Provides an output stream for sending
binary data to the client.
ServletContextEvent This is the event class for notifications
about changes to the servlet context of a
web application.
ServletContextAttributeEvent This is the event class for notifications
about changes to the attributes of the
servlet context of a web application.
ServletRequestEvent Events of this kind indicate lifecycle
events for a ServletRequest.
ServletRequestAttributeEvent This is the event class for notifications
of changes to the attributes of the
servlet request in an application.
package
Interface Description
Servlet Defines methods that all servlets must
implement.
ServletConfig A servlet configuration object used by
a servlet container to pass information
to a servlet during initialization.
ServletContext Defines a set of methods that a servlet
uses to communicate with its servlet
container, for example, to get the
MIME type of a file, dispatch requests,
or write to a log file.
ServletRequest Defines an object to provide client
request information to a servlet.
ServletResponse Defines an object to assist a servlet in
sending a response to the client.
RequestDispatcher Defines an object that receives
requests from the client and sends
them to any resource (such as a
servlet, HTML file, or JSP file) on the
server.
javax.servlet.http
 This package describe and define the contracts
between a servlet class running under the HTTP
protocol and the runtime environment provided for
an instance of such a class by a conforming servlet
container.
Classes available in javax.servlet package
Classes Description
Cookie Creates a cookie, a small amount of information sent by a servlet to a Web
browser, saved by the browser, and later sent back to the server.
HttpServlet Provides an abstract class to be subclassed to create an HTTP servlet suitable
for a Web site.
HttpServletRequestWrapper Provides a convenient implementation of the HttpServletRequest interface
that can be subclassed by developers wishing to adapt the request to a Servlet.
HttpServletResponseWrapper Provides a convenient implementation of the HttpServletResponse interface
that can be subclassed by developers wishing to adapt the response from a
Servlet.
HttpSessionBindingEvent Events of this type 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 configured in the
deployment descriptor when any attribute is bound, unbound or replaced in a
session.
HttpSessionEvent This is the class representing event notifications for changes to sessions
within a web application.
package
Interface Description
HttpServletRequest Extends the ServletRequest interface to provide
request information for HTTP servlets.
HttpServletResponse Extends the ServletResponse interface to provide
HTTP-specific functionality in sending a response.
HttpSession Provides a way to identify a user across more than
one page request or visit to a Web site and to store
information about that user.
HttpSessionActivationListener Objects that are bound to a session may listen to
container events notifying them that sessions will
be passivated and that session will be activated.
HttpSessionAttributeListener This listener interface can be implemented in order
to get notifications of changes to the attribute lists
of sessions within this web application.
HttpSessionBindingListener Causes an object to be notified when it is bound to
or unbound from a session.
HttpSessionListener Implementations of this interface are notified of
changes to the list of active sessions in a web
application.
Reading Servlet
Parameter
 Reading Form Data using Servlet
 Servlets handles form data parsing 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.
Handling HTTP Requests and
Responses
 HttpServlet class provides specialized methods
that handle the various types of HTTP requests. A
servlet developer typically overrides one of these
methods. These methods are doDelete( ), doGet(
), doHead( ), doOptions( ), doPost( ), doPut(
), and doTrace( ). However, the GET and POST
requests are commonly used when handling form
input.
 doGet and doPost are the commonly used methods
of HTTPServlet
Handling Http Request & Responses
S.N. Method and Description
1
GET The GET method is used to retrieve information from the given
server using a given URI. Requests using GET should only retrieve
data and should have no other effect on the data.
2
HEAD Same as GET, but transfers the status line and header section
only.
3
POST A POST request is used to send data to the server, for
example, customer information, file upload, etc. using HTML forms.
4
PUT Replaces all current representations of the target resource with
the uploaded content.
5
DELETE Removes all current representations of the target resource
given by a URI.
6
CONNECT Establishes a tunnel to the server identified by a given
URI.
7
OPTIONS Describes the communication options for the target
resource.
8
TRACE Performs a message loop-back test along the path to the
target resource.
Handling Http Request & Responses
 Get
 Its main job is to get some resource From server based on client request
 Total number of characters that get can carry to server is very less/limited.
 This appends URL with client request data
 One can Cache the requests of this type
 Requests parameters remain in browsing history
 Because of above limitations, GET is not supposed to used for complex and sensitive
requests
 Post
 Its main job is to send client data and get the resource from server based on client
request.
 Post can handle more characters that get can carry to server is very less/limited.
 This does not append client request data to URL
 These requests cannot be cached
 These do not remain in browsing history
 This is more preferred for complex and sensitive requests (like login)
Http Server Programming in JAVA - Handling http requests and responses
Tracking
 Cookies
 Cookies are small pieces of information that are
sent in response from the web server to the
client. Cookies are the simplest technique used for
storing client state.
 Cookies are stored on client's computer. They have
a lifespan and are destroyed by the client browser at
the end of that lifespan.
Servlet: Cookies API
 Cookies are created using Cookie class present in
Servlet API. Cookies are added to response object
using the addCookie() method. This method sends
cookie information over the HTTP response
stream. getCookies() method is used to access the
cookies that are added to response object.
Example
Session Tracking
 Session Tracking tracks a user’s requests and
maintains their state. It is a mechanism used to store
information on specific users and in order to
recognize these user’s requests when they connect to
the web server.
ILLUSTRATAION
If session tracking is not used, request 2 is treated as a new request without
the server recognizing that it is from the same use
Types of Cookies
 There are two types of cookies. They are as following:
 Session
 Persistent
 1) Session cookies:
 The session cookies do not have any expiration time. It is
present in the browser memory. When the web browser
is closed then the cookies are destroyed automatically.
 2) Persistent Cookies:
 The Persistent cookies have an expiration time. It is
stored in the hard drive of the user and it is destroyed
based on the expiry time.
Ad

More Related Content

What's hot (20)

Servlets
ServletsServlets
Servlets
ZainabNoorGul
 
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE AND JSP PROCESSING
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE  AND JSP PROCESSINGINTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE  AND JSP PROCESSING
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE AND JSP PROCESSING
Aaqib Hussain
 
Servlet
Servlet Servlet
Servlet
Dhara Joshi
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
Manisha Keim
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
kumar gaurav
 
Map Reduce
Map ReduceMap Reduce
Map Reduce
Prashant Gupta
 
Advanced java
Advanced java Advanced java
Advanced java
NA
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
Kasun Madusanke
 
Servlets
ServletsServlets
Servlets
Sasidhar Kothuru
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
Generics
GenericsGenerics
Generics
Ravi_Kant_Sahu
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 
Java RMI
Java RMIJava RMI
Java RMI
Prajakta Nimje
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
Smithss25
 
And or graph
And or graphAnd or graph
And or graph
Ali A Jalil
 
Database System Architectures
Database System ArchitecturesDatabase System Architectures
Database System Architectures
Information Technology
 
Android - Android Intent Types
Android - Android Intent TypesAndroid - Android Intent Types
Android - Android Intent Types
Vibrant Technologies & Computers
 
Ajax ppt
Ajax pptAjax ppt
Ajax ppt
OECLIB Odisha Electronics Control Library
 

Similar to Http Server Programming in JAVA - Handling http requests and responses (20)

Chap4 4 1
Chap4 4 1Chap4 4 1
Chap4 4 1
Hemo Chella
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, API
PRIYADARSINISK
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Tushar B Kute
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
vamsi krishna
 
Servlet by Rj
Servlet by RjServlet by Rj
Servlet by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
deepak kumar
 
Servlets
ServletsServlets
Servlets
Akshay Ballarpure
 
Servlet basics
Servlet basicsServlet basics
Servlet basics
Santosh Dhoundiyal
 
Java servlets
Java servletsJava servlets
Java servlets
yuvarani p
 
gayathri.pptx
gayathri.pptxgayathri.pptx
gayathri.pptx
GayathriP95
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
Emprovise
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
vikram singh
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
vikram singh
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
Fahmi Jafar
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
Ankit Minocha
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
Auwal Amshi
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
Praveen Yadav
 
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servletsSERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
RadhikaP41
 
Java servlets
Java servletsJava servlets
Java servlets
lopjuan
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, API
PRIYADARSINISK
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Tushar B Kute
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
vamsi krishna
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
Emprovise
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
vikram singh
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
vikram singh
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
Fahmi Jafar
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
Ankit Minocha
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
Auwal Amshi
 
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servletsSERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
RadhikaP41
 
Java servlets
Java servletsJava servlets
Java servlets
lopjuan
 
Ad

Recently uploaded (20)

Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Ad

Http Server Programming in JAVA - Handling http requests and responses

  • 2. HTTP Fundamentals  Introduction to HTTP  HTTP (Hypertext Transfer Protocol) is the foundation of data communication on the World Wide Web.  It is a request-response protocol used by web browsers and web servers to exchange data and information.  HTTP Request and Response  An HTTP request is made by a client (usually a web browser) to request resources from a web server.  An HTTP response is sent by the server to fulfill the client's request.  HTTP Methods  HTTP requests use methods like GET, POST, PUT, DELETE to define the type of request.  GET is used to retrieve data, POST to send data to be processed, PUT to update data, and DELETE to remove data.
  • 3. Servlet Programming  Introduction to Servlets  A servlet is a Java-based technology for building web applications.  Servlets run on the server-side and handle client requests and generate dynamic responses.  Servlet API  The Java Servlet API provides a framework for developing servlets.  It includes classes and interfaces for handling servlet requests and responses.  Creating a Servlet  To create a servlet, you need to extend the javax.servlet.http.HttpServlet class and override its doGet or doPost method.
  • 4. EXAMPLE public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet logic here } }
  • 5. Web Deployment Descriptor (web.xml)  The web.xml file is an XML configuration file that maps URLs to servlets. <servlet> <servlet-name>MyServlet</servlet-name> <servlet-class>com.example.MyServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServlet</servlet-name> <url-pattern>/myservlet</url-pattern> </servlet-mapping>
  • 6. The Life Cycle of a Servlet; Using Tomcat for Servlet Development  Initialization  When a servlet is first loaded, its init method is called.  You can perform one-time initialization tasks in this method.  Request Handling  For each client request, the servlet's service method is called.  The service method dispatches the request to the appropriate HTTP method (doGet, doPost, etc.).  Destruction  When the servlet container decides to unload the servlet, the destroy method is called.  You can perform cleanup tasks in this method.  Request and Response Objects  Servlets receive two important objects: HttpServletRequest for the request and HttpServletResponse for the response.  You can use these objects to access client data and send responses.
  • 7. Using Tomcat for Servlet Development  Apache Tomcat  Apache Tomcat is an open-source web server and servlet container.  It is widely used for running Java-based web applications, including servlets.  Setting up Tomcat  Download and install Tomcat from the Apache Tomcat website.  Configure your web application by placing servlet classes and the web.xml file in the appropriate directories.  Start Tomcat and deploy your web application.  Accessing Servlets  Servlets are accessed using a URL that maps to their URL pattern defined in web.xml.  For example, if a servlet is mapped to /myservlet, you can access it at http://localhost:8080/yourapp/myservlet.  Tomcat Manager  Tomcat provides a web-based manager application that allows you to deploy, undeploy, and manage your web applications.  You can access it at http://localhost:8080/manager/html.
  • 8. Servlets - Examples  Servlets are Java classes which service HTTP requests and implement the javax.servlet.Servlet interface.  Web application developers typically write servlets that extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface and is specially designed to handle HTTP requests.
  • 9. // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class HelloWorld extends HttpServlet { private String message; public void init() throws ServletException { // Do required initialization message = "Hello World"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); // Actual logic goes here. PrintWriter out = response.getWriter(); out.println("<h1>" + message + "</h1>"); } public void destroy() { // do nothing. } }
  • 10. Servlet Deployment  By default, a servlet application is located at the path <Tomcat-installationdirectory>/webapps/ROOT and the class file would reside in <Tomcat- installationdirectory>/webapps/ROOT/WEB- INF/classes.  If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class must be located in WEB- INF/classes/com/myorg/MyServlet.class.  For now, let us copy HelloWorld.class into <Tomcat- installationdirectory>/webapps/ROOT/WEB- INF/classes and create following entries in web.xml file located in <Tomcat-installation- directory>/webapps/ROOT/WEB-INF/
  • 12.  Above entries to be created inside <web-app>...</web- app> tags available in web.xml file. There could be various entries in this table already available, but never mind.  You are almost done, now let us start tomcat server using <Tomcat-installationdirectory>binstartup.bat (on Windows) or <Tomcat- installationdirectory>/bin/startup.sh (on Linux/Solaris etc.) and finally type http://localhost:8080/HelloWorld in the browser's address box. If everything goes fine, you would get the following result
  • 14. The Javax.servlet Package  The Java Servlet API is an acronym for Application Programming Interface (API) that is used on a server to interact with the other pages.  It communicates with the clients through a request and response format or system in a servlet container. An application programming interface (API) for servlets is a group of predefined packages, classes, and interfaces that have been written, along with their servlet methods and constructors.  It is a mechanism for interaction between two web application components and servlet functions.
  • 15. What is Servlet API?  Servlets are Java pieces of code on a web server or server-side that can handle Java.  We can manage the request from the remote server, process and operate the servlet request, make the servlet response, and then return the web page or server.  We can also use Servlets to make several web or Java-based applications. It must utilize the Servlet API, which includes all virtual interfaces and classes, to make Java Servlets.  Servlet API comes in two packages, which are:  javax.servlet  javax.servlet.http  The servlet pages or web container uses many interfaces and classes from the “javax.servlet” package. The “javax.servlet.http” package has classes and interfaces that manage http requests.
  • 16. Classes available in javax.servlet package Classes Description GenericServlet Defines a generic, protocol-independent servlet. ServletInputStream Provides an input stream for reading binary data from a client request, including an efficient readLine method for reading data one line at a time. ServletOutputStream Provides an output stream for sending binary data to the client. ServletContextEvent This is the event class for notifications about changes to the servlet context of a web application. ServletContextAttributeEvent This is the event class for notifications about changes to the attributes of the servlet context of a web application. ServletRequestEvent Events of this kind indicate lifecycle events for a ServletRequest. ServletRequestAttributeEvent This is the event class for notifications of changes to the attributes of the servlet request in an application.
  • 17. package Interface Description Servlet Defines methods that all servlets must implement. ServletConfig A servlet configuration object used by a servlet container to pass information to a servlet during initialization. ServletContext Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. ServletRequest Defines an object to provide client request information to a servlet. ServletResponse Defines an object to assist a servlet in sending a response to the client. RequestDispatcher Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server.
  • 18. javax.servlet.http  This package describe and define the contracts between a servlet class running under the HTTP protocol and the runtime environment provided for an instance of such a class by a conforming servlet container.
  • 19. Classes available in javax.servlet package Classes Description Cookie Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. HttpServlet Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. HttpServletRequestWrapper Provides a convenient implementation of the HttpServletRequest interface that can be subclassed by developers wishing to adapt the request to a Servlet. HttpServletResponseWrapper Provides a convenient implementation of the HttpServletResponse interface that can be subclassed by developers wishing to adapt the response from a Servlet. HttpSessionBindingEvent Events of this type 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 configured in the deployment descriptor when any attribute is bound, unbound or replaced in a session. HttpSessionEvent This is the class representing event notifications for changes to sessions within a web application.
  • 20. package Interface Description HttpServletRequest Extends the ServletRequest interface to provide request information for HTTP servlets. HttpServletResponse Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. HttpSession Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. HttpSessionActivationListener Objects that are bound to a session may listen to container events notifying them that sessions will be passivated and that session will be activated. HttpSessionAttributeListener This listener interface can be implemented in order to get notifications of changes to the attribute lists of sessions within this web application. HttpSessionBindingListener Causes an object to be notified when it is bound to or unbound from a session. HttpSessionListener Implementations of this interface are notified of changes to the list of active sessions in a web application.
  • 21. Reading Servlet Parameter  Reading Form Data using Servlet  Servlets handles form data parsing 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.
  • 22. Handling HTTP Requests and Responses  HttpServlet class provides specialized methods that handle the various types of HTTP requests. A servlet developer typically overrides one of these methods. These methods are doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and doTrace( ). However, the GET and POST requests are commonly used when handling form input.  doGet and doPost are the commonly used methods of HTTPServlet
  • 23. Handling Http Request & Responses S.N. Method and Description 1 GET The GET method is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data. 2 HEAD Same as GET, but transfers the status line and header section only. 3 POST A POST request is used to send data to the server, for example, customer information, file upload, etc. using HTML forms. 4 PUT Replaces all current representations of the target resource with the uploaded content. 5 DELETE Removes all current representations of the target resource given by a URI. 6 CONNECT Establishes a tunnel to the server identified by a given URI. 7 OPTIONS Describes the communication options for the target resource. 8 TRACE Performs a message loop-back test along the path to the target resource.
  • 24. Handling Http Request & Responses  Get  Its main job is to get some resource From server based on client request  Total number of characters that get can carry to server is very less/limited.  This appends URL with client request data  One can Cache the requests of this type  Requests parameters remain in browsing history  Because of above limitations, GET is not supposed to used for complex and sensitive requests  Post  Its main job is to send client data and get the resource from server based on client request.  Post can handle more characters that get can carry to server is very less/limited.  This does not append client request data to URL  These requests cannot be cached  These do not remain in browsing history  This is more preferred for complex and sensitive requests (like login)
  • 26. Tracking  Cookies  Cookies are small pieces of information that are sent in response from the web server to the client. Cookies are the simplest technique used for storing client state.  Cookies are stored on client's computer. They have a lifespan and are destroyed by the client browser at the end of that lifespan.
  • 27. Servlet: Cookies API  Cookies are created using Cookie class present in Servlet API. Cookies are added to response object using the addCookie() method. This method sends cookie information over the HTTP response stream. getCookies() method is used to access the cookies that are added to response object.
  • 29. Session Tracking  Session Tracking tracks a user’s requests and maintains their state. It is a mechanism used to store information on specific users and in order to recognize these user’s requests when they connect to the web server.
  • 30. ILLUSTRATAION If session tracking is not used, request 2 is treated as a new request without the server recognizing that it is from the same use
  • 31. Types of Cookies  There are two types of cookies. They are as following:  Session  Persistent  1) Session cookies:  The session cookies do not have any expiration time. It is present in the browser memory. When the web browser is closed then the cookies are destroyed automatically.  2) Persistent Cookies:  The Persistent cookies have an expiration time. It is stored in the hard drive of the user and it is destroyed based on the expiry time.