Http Server Programming in JAVA - Handling http requests and responses

946 views 31 slides Dec 13, 2023
Slide 1
Slide 1 of 31
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31

About This Presentation

This ppt contains HTML forms and CGI; HTTP; Servlet Programming; The Life Cycle of a
Servlet; Using Tomcat for Servlet Development; A simple Servlet;
deployment of simple servlets, web server (Java web server / Tomcat/ Web
logic) The Servlet API; The Javax.servlet Package; Reading Servlet
Pa...


Slide Content

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 >\bin\startup.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

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.

Interface available in javax.servlet 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.

Interface available in javax.servlet 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)

Using Cookies; Session 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 .

E xample

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.