Sie sind auf Seite 1von 70

HTTP

HTTP Hyper Text Transfer Protocol HTTP defines the requests that a client can send to a server and responses that the server can send in reply. Each request contains a URL, which is a string that identifies a Web component or a static object such as an HTML page or image file.

HTTP Requests

A HTTP request consist


request method Indicates action to be taken by server a request URL Universal Resource Locator. Indicates the resource requested such a html document, image and so on header fields contains other information such browser name, version, its capabilities and so on Body additional information for processing request. It may contain data provided by user such as username, password etc.
2

 GET: Retrieves the resource identified by the request URL [HTTP1.0]  HEAD: Returns the headers identified by the request URL [HTTP1.0]  POST: Sends data of unlimited length to the Web server [HTTP1.0]  PUT: Stores a resource under the request URL [HTTP1.1]  DELETE: Removes the resource identified by the request URL [HTTP1.1]  OPTIONS: Returns the HTTP methods the server supports [HTTP1.1]  TRACE: Returns the header fields sent with the TRACE request [HTTP1.1]
3

Request Methods

 A HTTP Response contain a


Result Code indicates status of the request such as success, failure etc
 404: Indicates that the requested resource is not available  401: Indicates that the request requires HTTP authentication  500: Indicates that an error occurred inside the HTTP server that prevented  it from fulfilling the request  503: Indicates that the HTTP server is temporarily overloaded and unable  to handle the request

Header Fields Body Content of the response. It could be a html document, a image file etc.
4

Client-Server Interaction

Browser

http://xxx.com http://xxx.com

Browser

Web Server

Documents Browser Server Machine

Client-Server Interaction
 Web server receives a request for document  Checks if document is available  If present, returns the document  Browser renders the document  A simple web-server would return document as it is entire content of document  A simple Web server is in a way dumb document supplier.
Please remember sending a document basically means server reads the file, sends stream of bytes to the browser.
6

J2EE Servlet Container


J2EE Server or Web Servers with Servlet container such as Tomcat convert HTTP requests. A HTTP request is converted into java request object. Then Passed to servlet. Servlets Return response objects. Response object is converted to HTTP response and delivered to client
7

Servlet

Browser
http://xxx.com http://xxx.com

Servlet Container

Browser

Web Server

Browser
Documents Server Machine

Clint-Servlet Container Interaction

 Request would go to webserver  If the request is not for static document, web server redirects the request to servelet container.  Servlet container checks if the servlet is already loaded.  If not then load the servlet and intializes.  Execute servlet (service method).  Servlet provides dynamic content to be sent.  Webserver returns the content to Browser  Browser renders the content.

Why Servlet?

 Servlet/JSPs come into picture when the content (response to client) needs to be generated dynamically.  You can treat servlets as entities which create documents (content) to be sent to browser.  The document is created every time it is requested.  Since the document is created every time, you can put the logic to alter the content of the document based some condition.  This is how we can generate dynamic content using servlets.

10

Simple Web-Server Activities


        Keep listening for request from clients(browsers) Receive requests Check if the request is appropriate HTTP request Check if all the necessary information is present in the request so that response can be sent back Understanding the request Locating the resource in with server area Forming response with the data to be sent back sending the response

11

Container Activities

 If the request is for servlet initiate loading the servlet  See if are there any information (initiation parameters) to be provided while creating a servlet  Create Request object out of http-request from browser  Create Response object for servlet to fill in the information  Provide facility for more than one servlet share common resources such as database connection.

12

Container Activities
 Clean up before servlet needs to be destroyed.  Manage situation when a servlet is serving a request from one client a request from another client arrives.  Session tracking information exchange across requests  Build the service method  Execute Service method of servlet  Create HTTP response from response object  send the response back to client

13

Do we need to that all?


 Most of the green activities listed in earlier slides are regular and routine.  All these activities needs to be performed in same way no matter weather the application is online shopping, search site, mail application etc.  The question does every application developer need to write code do this? Why?  Is it not possible provide application which does all these things and developer only needs to develop her application logic?
14

Web answer is Yes. Container  The


 That is what a web container would do.  A web container would do all the green stuff for you and may only have focus on read stuff !!  Thus a Web Container is essential a Java runtime framework which allows you plug-in your web application.  You only build your application logic, web container will manage the headache of keeping client engaged.  It's like an expert surgeon performing operation at reputed hospital you go there perform your surgery. Hospital will manage admitting patient, arrange OT, providing post operation facility, billing the patient, collecting money and paying your fee.

15

Servlet
A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications they are commonly used to extend the applications hosted by web servers To work with Servlet a servlet container is must Java Servlet technology defines HTTPspecific servlet classes
16

Servlet
javax.servlet - provide interfaces javax.servlet.http - classes for writing servlets All servlets must implement the Servlet interface directly or indirectly HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.

17

Servlet Example
import java.io.IOException; import java.io.PrintWriter; import java.util.GregorianCalendar; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

Makes your class a servlet

public class firstServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) ServletException, IOException {
response.setContentType("text/html"); PrintWriter out = response.getWriter(); GregorianCalendar cal = new GregorianCalendar(); String date = cal.get(cal.DATE)+"/"+cal.get(cal.MONTH)+"/"+cal.get(cal.YEAR); String time = cal.get(cal.HOUR)+":"+cal.get(cal.MINUTE)+":"+cal.get(cal.SECOND); System.out.println(request.getMethod()); out.write("<html>"); out.write("<body>"); out.write("<h1>This is my first Servlet</h1>"); out.write("<h2>Date" + date + "</h2>"); out.write("<h2>Time" + time + "</h2>"); out.write("</body>"); out.write("</html>");

GET request arrives from client this method will be called


throws

Stuff that needs to go to Client Dynamic content something you can not do with html alone

} }

18

Tomcat Container Structure

19

Deploying Servlet
 Assume Tomcat is installed at
/opt/tomcat -> will call it as TOMCAT_HOME

 Lets also assume that your webapp name is - MyFirst  Step 1: creating directory structure  Step 2:Create Context Descriptor  Step 3: Create Deployment Descriptor Web.xml  Step 4: Place your servlet class  Step 5: Restart server
20

Step 1: Create Directory Structure

Create following directory structure under webapps

21

Step 2:Create Context Descriptor

Create a text file called MyFirst.xml. Put following line to the file
<Context path="/MyFirst" docBase="MyFirst" debug="0" reloadable="true"/>

Context descriptor file has put under


TOMCAT_HOME/conf/Catalina/localhost/

22

Step 3: Create Deployment Descriptor - Web.xml

Create a descriptor file as shown below in


TOMCAT_HOME/webapps/MyFirst/WEB-INF <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app //Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> PUBLIC "Name of the Servlet and class. With this it is possible to load two servlet instances in different names

<servlet-name> firstServlet </servlet-name> <servlet-class> firstServlet </servlet-class> </servlet>

<servlet-mapping>

Mapping Servelt to URL this is how it would be referred <servlet-name> firstServlet </servlet-name> http://localhost:8080/MyFirst/
ServletTest

<url-pattern>/ServletTest</url-pattern> </servlet-mapping> </web-app>


23

Step 4: Place your servlet class

Compile your Servlet class. Please remember you would need Servlet API jar to compile your servlet. Servlet API jar can be located in
TOMCAT_HOME/common/lib/servlet-api.jar

Copy your servelts .class file to


TOMCAT_HOME/webapps/WE-NF/classes

24

Step 5: Restart server


Restart Tomcat
TOMCAT_HOME/bin/startup.sh [ startup.bat for windows]

Access your Servlet with following URL


http://localhost:8080/MyFirst/ServeletTest

25

Discussion

26

27

Working With Servlets

28

Generic Servlet Package javax.servelt


servlet + init() +service(request,response) +destroy() ServletConfig SingleThreadModel

GenericServlet Servlet Response ServletRequest

ServletContext

ServiceException

RequestDispatcher OutputStream InputStream

Class

Interface

Association Dependency
29

HTTP Servlet
Package javax.servlet.http defines interfaces and classes for HTTP servlet implementation This basically means servlets which follow http protocol This package defines various interfaces and classes for developer to work with servlet.

30

javax.servlet.http
 Servlet Implementation

 The classes and interfaces present in this package can divided based on purpose of design
Stuff related to implementation of servlets

 Servlet Configuration
Help provide configuration information to servlet. User can provide configuration parameters which servelt can use during exection

 Servlet Exception
Facility for handling Exceptional situations

 Request and Response


Request and Response interfaces. Provide all the facility to get information of request and form appropriate response

 Session Tacking
Facility for tracking client session. With this client interactions can be made stateful

 Servlet Context
Facility to share and set information and data with other servelts in the same web application
31

Excercise
Refer Servlet API
Generic Servlet Hirarchy HttpServlet Hierarchy HttpRequest Hierarchy HttpResponse Hierarchy

Identify bases classes and interfaces and important methods and describe them.

32

Servlet Life Cycle

33

   

Methods in Servlet Interface

Void init(ServletConfig config) Void service(ServletRequest req, ServletResponse res) String getServletInfo() ServletConfigget ServletConfig()

34

HttpServlet
Derived from Generic Servlet Java class which defines methods to handle HTTP request such as post, get etc.

35

HttpServlet
Following Methods must be overridden
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws vletException,java.io.IOException  protected void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException, java.io.IOException  protected void doDelete(HttpServletRequest req,HttpServletResponse resp)throws ServletException,java.io.IOException basically tells the options supported. No need to override  protected void doPut(HttpServletRequest req,HttpServletResponse resp)throws ServletException,java.io.IOException

36

HttpServletRequest
This interface provides the details of the HTTP request It provides information such as request header information, HTTP request method and many more.

37

Methods of HTTP Request


Method Summary
java.lang.String getAuthType() Returns the name of the authentication scheme used to protect the servlet. java.lang.String getContextPath() Returns the portion of the request URI that indicates the context of the request. Cookie[] getCookies() Returns an array containing all of the Cookie objects the client sent with this request. long getDateHeader(java.lang.String name) Returns the value of the specified request header as a long value that represents a Date object. java.lang.String getHeader(java.lang.String name) Returns the value of the specified request header as a String. java.util.Enumera getHeaderNames() Returns an enumeration of all the header names this request contains. tion java.util.Enumera getHeaders(java.lang.String name) Returns all the values of the specified request header as an Enumeration of tion String objects. int getIntHeader(java.lang.String name) Returns the value of the specified request header as an int. java.lang.String getMethod() Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. java.lang.String getPathInfo() Returns any extra path information associated with the URL the client sent when it made this request. java.lang.String getPathTranslated() Returns any extra path information after the servlet name but before the query string, and translates it to a real path. java.lang.String getQueryString() Returns the query string that is contained in the request URL after the path.

38

Methods of HTTP Request


Method Summary
java.lang.String getRemoteUser() Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated. java.lang.String getRequestedSessionId() Returns the session ID specified by the client. java.lang.String getRequestURI() Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request. java.lang.StringB getRequestURL() Reconstructs the URL the client used to make the request. uffer java.lang.String getServletPath() Returns the part of this request's URL that calls the servlet. HttpSession getSession() Returns the current session associated with this request, or if the request does not have a session, creates one. HttpSession getSession(boolean create) Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session. java.security.Prin getUserPrincipal() Returns a java.security.Principal object containing the name of the current cipal authenticated user. boolean isRequestedSessionIdFromCookie() Checks whether the requested session ID came in as a cookie. boolean isRequestedSessionIdFromUrl() Deprecated. As of Version 2.1 of the Java Servlet API, use isRequestedSessionIdFromURL() instead. boolean isRequestedSessionIdFromURL() Checks whether the requested session ID came in as part of the request URL. boolean isRequestedSessionIdValid() Checks whether the requested session ID is still valid. boolean isUserInRole(java.lang.String role) Returns a boolean indicating whether the authenticated user is included in the specified logical "role".

39

HTTP Response Methods


Method Summary
void addCookie(Cookie cookie) Adds the specified cookie to the response. void addDateHeader(java.lang.String name, long date) Adds a response header with the given name and datevalue. void addHeader(java.lang.String name, java.lang.String value) Adds a response header with the given name and value. void addIntHeader(java.lang.String name, int value) Adds a response header with the given name and integer value. boolean containsHeader(java.lang.String name) Returns a boolean indicating whether the named response header has already been set. java.lang encodeRedirectURL(java.lang.String url) .String Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged. encodeURL(java.lang.String url) Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. sendError(int sc) Sends an error response to the client using the specified status code and clearing the buffer. sendError(int sc, java.lang.String msg)

java.lang .String void

void

Sends an error response to the client using the specified status. void sendRedirect(java.lang.String location) Sends a temporary redirect response to the client using the specified redirect location URL. void setDateHeader(java.lang.String name, long date) Sets a response header with the given name and date-value. void setHeader(java.lang.String name, java.lang.String value) Sets a response header with the given name and value. void setIntHeader(java.lang.String name, int value) Sets a response header with the given name and integer value. void setStatus(int sc) Sets the status code for this response.

40

Session
A session is basically a set of HTTP transaction between client and server HTTP it self is stateless protocol. It can not remember what transpired in last request. If web application need information flow from one request to another, an application level session needs to be created and managed.
41

Methods Session Tracking


 URL rewriting Information obtained in last request is sent client in such a way that it comes back to server in next request  Hidden form fields Create hidden fields in the which will resubmitted in the next submit  Coockies- A cookie is small piece of textual information sent by the server to the client, stored on the client, and returned by the client for all requests to the server. Cookie contains one or more name=value pairs
42

Session with Servlet


With servlets session management is handled by servlet container. javax.servlet.http package defines HttpSession interface A session object can be obtained from HttpServletRequest object by calling
getSession() getSession(boolean create)

43

Session Interface Methods


Method Summary
java.lang.Object getAttribute(java.lang.String name) Returns the object bound with the specified name in this session, or null if no object is bound under the name. java.util.Enumeration getAttributeNames() Returns an Enumeration of String objects containing the names of all the objects bound to this session. long getCreationTime() Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. java.lang.String getId() Returns a string containing the unique identifier assigned to this session. long getLastAccessedTime() Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT, and marked by the time the container received the request. int getMaxInactiveInterval() Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. ServletContext getServletContext() Returns the ServletContext to which this session belongs. void invalidate() Invalidates this session then unbinds any objects bound to it. boolean isNew() Returns true if the client does not yet know about the session or if the client chooses not to join the session. void removeAttribute(java.lang.String name) Removes the object bound with the specified name from this session. void setAttribute(java.lang.String name, java.lang.Object value) Binds an object to this session, using the name specified. void setMaxInactiveInterval(int interval) Specifies the time, in seconds, between client requests before the servlet container will invalidate this session.

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

Das könnte Ihnen auch gefallen