Escolar Documentos
Profissional Documentos
Cultura Documentos
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
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
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
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
Servlet
Browser
http://xxx.com http://xxx.com
Servlet Container
Browser
Web Server
Browser
Documents Server Machine
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
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
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;
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>");
Stuff that needs to go to Client Dynamic content something you can not do with html alone
} }
18
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
21
Create a text file called MyFirst.xml. Put following line to the file
<Context path="/MyFirst" docBase="MyFirst" debug="0" reloadable="true"/>
22
<servlet-mapping>
Mapping Servelt to URL this is how it would be referred <servlet-name> firstServlet </servlet-name> http://localhost:8080/MyFirst/
ServletTest
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
24
25
Discussion
26
27
28
ServletContext
ServiceException
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
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
33
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
38
39
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
43
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