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.

More Related Content

What's hot (20)

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
 
Java beans
Java beansJava beans
Java beans
Rajkiran Mummadi
 
RPC: Remote procedure call
RPC: Remote procedure callRPC: Remote procedure call
RPC: Remote procedure call
Sunita Sahu
 
Principal source of optimization in compiler design
Principal source of optimization in compiler designPrincipal source of optimization in compiler design
Principal source of optimization in compiler design
Rajkumar R
 
Concurrency control
Concurrency controlConcurrency control
Concurrency control
Subhasish Pati
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
FAKHRUN NISHA
 
Domain State model OOAD
Domain State model  OOADDomain State model  OOAD
Domain State model OOAD
Raghu Kumar
 
Recursive Descent Parsing
Recursive Descent Parsing  Recursive Descent Parsing
Recursive Descent Parsing
Md Tajul Islam
 
Validation Controls in asp.net
Validation Controls in asp.netValidation Controls in asp.net
Validation Controls in asp.net
Deep Patel
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
sandeep54552
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
slire
 
Transaction management in DBMS
Transaction management in DBMSTransaction management in DBMS
Transaction management in DBMS
Megha Sharma
 
Design of Hadoop Distributed File System
Design of Hadoop Distributed File SystemDesign of Hadoop Distributed File System
Design of Hadoop Distributed File System
Dr. C.V. Suresh Babu
 
operating system structure
operating system structureoperating system structure
operating system structure
Waseem Ud Din Farooqui
 
Concurrency control
Concurrency  controlConcurrency  control
Concurrency control
Javed Khan
 
Process synchronization in Operating Systems
Process synchronization in Operating SystemsProcess synchronization in Operating Systems
Process synchronization in Operating Systems
Ritu Ranjan Shrivastwa
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
Java layoutmanager
Java layoutmanagerJava layoutmanager
Java layoutmanager
Arati Gadgil
 
Java Beans
Java BeansJava Beans
Java Beans
Ankit Desai
 
Java servlets
Java servletsJava servlets
Java servlets
lopjuan
 
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
 
RPC: Remote procedure call
RPC: Remote procedure callRPC: Remote procedure call
RPC: Remote procedure call
Sunita Sahu
 
Principal source of optimization in compiler design
Principal source of optimization in compiler designPrincipal source of optimization in compiler design
Principal source of optimization in compiler design
Rajkumar R
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
FAKHRUN NISHA
 
Domain State model OOAD
Domain State model  OOADDomain State model  OOAD
Domain State model OOAD
Raghu Kumar
 
Recursive Descent Parsing
Recursive Descent Parsing  Recursive Descent Parsing
Recursive Descent Parsing
Md Tajul Islam
 
Validation Controls in asp.net
Validation Controls in asp.netValidation Controls in asp.net
Validation Controls in asp.net
Deep Patel
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
slire
 
Transaction management in DBMS
Transaction management in DBMSTransaction management in DBMS
Transaction management in DBMS
Megha Sharma
 
Design of Hadoop Distributed File System
Design of Hadoop Distributed File SystemDesign of Hadoop Distributed File System
Design of Hadoop Distributed File System
Dr. C.V. Suresh Babu
 
Concurrency control
Concurrency  controlConcurrency  control
Concurrency control
Javed Khan
 
Process synchronization in Operating Systems
Process synchronization in Operating SystemsProcess synchronization in Operating Systems
Process synchronization in Operating Systems
Ritu Ranjan Shrivastwa
 
Java layoutmanager
Java layoutmanagerJava layoutmanager
Java layoutmanager
Arati Gadgil
 
Java servlets
Java servletsJava servlets
Java servlets
lopjuan
 

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

Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
deepak kumar
 
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
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
Praveen Yadav
 
Servlet by Rj
Servlet by RjServlet by Rj
Servlet by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
Ankit Minocha
 
Module 4.pptModule 4.pptModule 4.pptModule 4.ppt
Module 4.pptModule 4.pptModule 4.pptModule 4.pptModule 4.pptModule 4.pptModule 4.pptModule 4.ppt
Module 4.pptModule 4.pptModule 4.pptModule 4.ppt
tahirnaquash2
 
Chap4 4 1
Chap4 4 1Chap4 4 1
Chap4 4 1
Hemo Chella
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
MouDhara1
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
kstalin2
 
Servlet1.ppt
Servlet1.pptServlet1.ppt
Servlet1.ppt
KhushalChoudhary14
 
Servlet (1) also contains code to create it.ppt
Servlet (1) also contains code to create it.pptServlet (1) also contains code to create it.ppt
Servlet (1) also contains code to create it.ppt
juhishrivastava25
 
Servlets
ServletsServlets
Servlets
Manav Prasad
 
Servlet123jkhuiyhkjkljioyudfrtsdrestfhgb
Servlet123jkhuiyhkjkljioyudfrtsdrestfhgbServlet123jkhuiyhkjkljioyudfrtsdrestfhgb
Servlet123jkhuiyhkjkljioyudfrtsdrestfhgb
shubhangimalas1
 
Servlets
ServletsServlets
Servlets
ramesh kumar
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
Arumugam90
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
team11vgnt
 
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
 
Servlets api overview
Servlets api overviewServlets api overview
Servlets api overview
ramya marichamy
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 
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
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
Ankit Minocha
 
Module 4.pptModule 4.pptModule 4.pptModule 4.ppt
Module 4.pptModule 4.pptModule 4.pptModule 4.pptModule 4.pptModule 4.pptModule 4.pptModule 4.ppt
Module 4.pptModule 4.pptModule 4.pptModule 4.ppt
tahirnaquash2
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
kstalin2
 
Servlet (1) also contains code to create it.ppt
Servlet (1) also contains code to create it.pptServlet (1) also contains code to create it.ppt
Servlet (1) also contains code to create it.ppt
juhishrivastava25
 
Servlet123jkhuiyhkjkljioyudfrtsdrestfhgb
Servlet123jkhuiyhkjkljioyudfrtsdrestfhgbServlet123jkhuiyhkjkljioyudfrtsdrestfhgb
Servlet123jkhuiyhkjkljioyudfrtsdrestfhgb
shubhangimalas1
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
Arumugam90
 
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
 
Ad

Recently uploaded (20)

Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptxRai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
National Information Standards Organization (NISO)
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18
Celine George
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
Quiz Club of PSG College of Arts & Science
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18
Celine George
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
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.