Académique Documents
Professionnel Documents
Culture Documents
Servlet
A servlet is a web component, managed by a container, that generates dynamic content. It is a server-side program written in Java. After writing the source code, it has to be compiled into a class file, like any Java program. Whenever a HTTP request comes, requesting for the execution of this Servlet, the class file is interpreted by the Java Virtual Machine (JVM). This produces HTML output and is sent back to the browser in the form of HTTP response.
2
Why Servlets?
Web pages with dynamic content Easy coordination between Servlets to make Web applications Containers support many features
HTTP
Servlet job
Read explicit data sent by client (form data) Read implicit data sent by client (request headers) Generate the results Send the explicit data back to client (HTML) Send the implicit data to client (status codes and response headers)
When Servlets?
Receive Request for Servlet S Loaded when first used, or after modified no
CGI Scripts
client
server
script
client
Servlets
server
servlet
client
Running a servlet doesnt require creating a separate process each time (threads used) A servlet stays in memory, so it doesnt have to be reloaded each time There is only one instance handling multiple requests, not a separate instance for every request A variety of different languages were used to build CGI programs. These included C, C++, and Perl. Where as Servlet are coded in java
9
10
Portability
Power
Harness the full power of the core Java APIs: networking and URL access, multithreading, image manipulation, data compression, JDBC.
Safety
Support safe programming since inherit Javas strong type safety, exception-handling mechanism.
Security
the Java security manager on the server enforces a set of restrictions to protect the resources on a server machine Code is clean, object-oriented, modular, and simple (i.e.. Session tracking, cookie).
Elegance
Integration
Tightly integrated with the servertranslate file paths, perform logging, check authorization, and MIME type mapping.
12
13
Servlet Container
A servlet runs inside a Servlet container. A Servlet container is the hosting environment for Java Servlets. A compiler plus run-time hosting environment for Servlets.
What is HTTP
Hypertext Transfer Protocol is used to describe how HTML documents are sent over the Internet. It is stateless protocol HTTP Request Model
A client application, such as web browser opens a socket to the web servers HTTP port (80) Through the connection, the client writes an ASCII text request line, followed by zeros and more HTTP headers, an empty line, and any data that accompanies the request The web server parses the request and locates the specified resource The server writes a copy of the resource to the socket, where its read by the client The server closes the connection
15
GET
HEAD
OPTIONS
TRACE CONNECT
A request for information about what request methods the server supports
A request for the web server to echo the HTTP request and its headers A documented but currently unimplemented method reserved for use with a tunneling proxy.
16
4.
The browser sends an HTTP request to the Web server for executing a Servlet. The Web server hands it over to the servlet container, after providing the appropriate execution environment. The Servlet container loads and executes the Servlet (.class file of the Servlet) by interpreting its contents via the JVM. The result is usually some HTML output. This HTML output is sent back to the Web browser via the web server, as a part of the HTTP response.
17
Apache
Apache is:
18
Ports
Ports are identified by positive integers A port is a software notion, not a hardware notion, so there may be very many of them Typical port numbers:
21FTP, File Transfer Protocol 22SSH, Secure Shell 25SMTP, Simple Mail Transfer Protocol These are the ports 53DNS, Domain Name Service of most interest to us 80HTTP, Hypertext Transfer Protocol 8080HTTP (used for testing HTTP) 7648, 7649CU-SeeMe
19
Tomcat
Tomcat is the Servlet Engine than handles servlet requests for Apache
Tomcat is a helper application for Apache Its best to think of Tomcat as a servlet container
21
Servlet lifecycle
22
23
24
The server invokes the init( ) method of the servlet. This method is invoked only when the servlet is first loaded into memory. It is possible to pass initialization parameters to the servlet so it may configure itself. The server invokes the service( ) method of the servlet. This method is called to process the HTTP request. You will see that it is possible for the servlet to read data that has been provided in the HTTP request. It may also formulate an HTTP response for the client.
25
The servlet remains in the servers address space and is available to process any other HTTP requests received from clients. The service( ) method is called for each HTTP request. Finally, the server may decide to unload the servlet from its memory. The algorithms by which this determination is made are specific to each server. The server calls the destroy( ) method to relinquish any resources such as file handles that are allocated for the servlet. Important data may be saved to a persistent store. The memory allocated for the servlet and its objects can then be garbage collected.
26
First install j2sdk1.4.2_13 for access of Java classes & interfaces as the servlet is written in Java language. Set the environment variable PATH to c:\j2sdk1.4.2_13\bin; c:\j2sdk1.4.2_13\lib Next install Tomcat Create a new SYSTEM environment variable CLASSPATH to c:\Program Files\Apache Group\Tomcat 4.1\common\lib\servlet.jar Alternatively, you can specify this class file when you compile the servlets. For example, the following command compiles the first servlet example: javac HelloServlet.java -classpath "C:\Program Files\Apache Tomcat 4.0\common\lib\servlet.jar" To execute already provided examples of servlet In Internet Explorer add the URL http://localhost:8080
27
Execution in Tomcat
Create .java file in c:\j2sdk1.4.2_13\bin Compile it there using javac filename.java Copy the .class file to Tomcat server. C:\Program Files\Apache Group\Tomcat 4.1\webapps\examples\WEB-INF\classes\ Start the Tomcat server and minimize the window. Open Internet Explorer and in the URL enter http://localhost:8080/examples/servlet/filename
28
29
30
Explanation of program
First, note that it imports the javax.servlet package. This package contains the classes and interfaces required to build servlets. Next, the program defines HelloServlet as a subclass of GenericServlet. The GenericServlet class provides functionality that makes it easy to handle requests and responses. Inside HelloServet, the service( ) method (which is inherited from GenericServlet) is overridden. This method handles requests from a client. Notice that the first argument is a ServletRequest object. This enables the servlet to read data that is provided via the client request. The second argument is a ServletResponse object. This enables the servlet to formulate a response for the client. The call to setContentType( ) establishes the MIME type of the HTTP response. In this program, the MIME type is text/html. This indicates that the browser should interpret the content as HTML source code. Next, the getWriter( ) method obtains a PrintWriter. Anything written to this stream is sent to the client as part of the HTTP response. 31 Then println( ) is used to write some simple HTML source code as the HTTP response.
Start Tomcat
As explained, to start Tomcat, select Start Tomcat in the Start | Programs menu, or run startup.bat from the C:\Program Files\Apache Tomcat 4.0\bin\directory.
32
http://localhost:8080/examples/servlet/HelloS ervletpro
http://127.0.0.1:8080/examples/servlet/Hello Servletpro
33
Servlet Architecture
javax.servlet.Servlet interface javax.servlet.GenericServlet and javax.servlet.http.HttpServlet class Sun has provided a Java class called HttpServlet having methods for initialization, servicing, and destruction of Servlets. A new Servlet has to be written by extending from HttpServlet class.
34
35
36
37
Servlet Interface
38
ServletConfig Interface
39
ServletContext Interface
40
ServletRequest Interface
41
ServletRequest Interface
42
ServletRequest Interface
43
ServletResponse Interface
44
SingleThreadModel Interface
only a single thread will execute the service( ) at a time First, it can create several instances of the servlet. Second, it can synchronize access to the servlet No constant, no methods declared
45
GenericServlet Class
Basic life cycle of servlet Implements servlet and servletconfig interface void log(String s) void log(String s, Throwable e)
46
ServletInputStream Class
Extends InputStream Implemented by the server It defines the default constructor. int readLine(byte[ ] buffer, int offset, int size) throws IOException Here, buffer is the array into which size bytes are placed starting at offset. The method returns the actual number of bytes read or 1 if an end-ofstream condition is encountered.
47
ServletOutputStream Class
extends OutputStream implemented by the server A default constructor is defined. the print( ) and println( ) methods
48
49
Servlets
In practice, most servlets extend the javax.servlet.http.HttpServlet class Some servlets extend javax.servlet.GenericServlet instead
Servlets, like applets, usually lack a main method, but must implement or override certain other methods
50
Example
<html> <body> <center> <form name=f1" method="post" action="http://localhost:8080/examples/servlet/PostParametersServlet"> <table> <tr> <td><B>Employee</td> <td><input type=textbox name="e" size="25" value=""></td> </tr> <tr> <td><B>Phone</td> <td><input type=textbox name="p" size="25" value=""></td> </tr> </table> <input type=submit value="Submit"> </body> </html>
51
Example
import java.io.*; import java.util.*; import javax.servlet.*; public class PostParametersServlet extends GenericServlet { public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { // Get print writer. PrintWriter pw = response.getWriter(); // Get enumeration of parameter names. Enumeration e = request.getParameterNames(); // Display parameter names and values. while(e.hasMoreElements()) { String pname = (String)e.nextElement(); pw.print(pname + " = "); String pvalue = request.getParameter(pname); pw.println(pvalue); } pw.close(); } }
PostParametersServlet.java
52
How to Run
Compile the servlet and perform these steps to test this example: 1. Start Tomcat (if it is not already running). 2. Display the Web page in a browser. 3. Enter an employee name and phone number in the text fields. 4. Submit the Web page.
53
javax.servlet.http Package
54
HttpServletRequest
55
56
57
HttpServletResponse
58
59
HttpSession
All of these methods throw an IllegalStateException if the session has already been invalidated
60
61
HttpSessionBindingListener
Is implemented by objects that need to be notified when they are bound to or unbound from an HTTP session. void valueBound(HttpSessionBindingEvent e) void valueUnbound(HttpSessionBindingEvent e) Here, e is the event object that describes the binding.
62
Cookie Class
A cookie is stored on a client and contains state information. Cookies are valuable for tracking user activities A servlet can write a cookie to a users machine via the addCookie( ) method of the HttpServletResponse interface Cookie data includes The name of the cookie The value of the cookie The expiration date of the cookie The domain and path of the cookie Constructor
63
Cookie Class
64
65
HttpServlet Class
66
67
HttpSessionEvent Class
It encapsulates session events It extents EventObject and is generated when a change occurs to the session HttpSessionEvent(HttpSession session)
HttpSession getSession( )
68
HttpSessionBindingEvent Class
It extends HttpSessionEvent HttpSessionBindingEvent(HttpSession session, String name) HttpSessionBindingEvent(HttpSession session, String name, Object val)
Here, session is the source of the event and name is the name associated with the object that is being bound or unbound. If an attribute is being bound or unbound, its value is passed in val.
69
methods
String getName( )
HttpSession getSession( )
Object getValue( )
70
Servlets
In practice, most servlets extend the javax.servlet.http.HttpServlet class Some servlets extend javax.servlet.GenericServlet instead
Servlets, like applets, usually lack a main method, but must implement or override certain other methods
71
When a servlet is first started up, its init(ServletConfig config) method is called init should perform any necessary initializations init is called only once, and does not need to be thread-safe (syncronization not required) Every servlet request results in a call to service(ServletRequest request, ServletResponse response) service calls another method depending on the type of service requested Usually you would override the called methods of interest, not service itself service handles multiple simultaneous requests, so it and the methods it calls must be thread safe (syncronization required)
When the servlet is shut down, destroy() is called destroy is called only once, but must be thread safe (because other threads may still be running)
72
HTTP requests
When a request is submitted from a Web page, it is almost always a GET or a POST request The HTTP <form> tag has an attribute action will be the URL,method whose value can be "get" or "post" The "get" action results in the form information being put after a ? in the URL
Example: http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF8&q=servlets The & separates the various parameters Only a limited amount of information can be sent this way
73
The service method dispatches the following kinds of requests: DELETE, GET, HEAD, OPTIONS, POST, PUT, and TRACE
A GET request is dispatched to the doGet(HttpServletRequest request, HttpServletResponse response) method A POST request is dispatched to the doPost(HttpServletRequest request, HttpServletResponse response) method
These are the two methods you will usually override doGet and doPost typically do the same thing, so usually you do the real work in one, and have the other just call it
74
The browsers HTTP request is sent to the server. The servlets doGet() method receives this request as a parameter. Similarly, when the server needs to send back an HTTP response, it populates the corresponding attributes or calls methods in the other parameter HttpServletResponse, which is used to send back information to the browser in the form of an HTTP response.
75
http://localhost:8080/examples/servlet/HelloServlet
76
The superclass
public class HelloServlet extends HttpServlet { Every class must extend GenericServlet or a subclass of GenericServlet GenericServlet is protocol independent, so you could write a servlet to process any protocol In practice, you almost always want to respond to an HTTP request, so you extend HttpServlet A subclass of HttpServlet must override at least one method, usually one doGet, doPost, doPut, doDelete, init and destroy, or getServletInfo
77
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { This method services a GET request The method uses request to get the information that was sent to it The method does not return a value; instead, it uses response to get an I/O stream, and outputs its response Since the method does I/O, it can throw an IOException Any other type of exception should be encapsulated as a ServletException The doPost method works exactly the same way
78
Parameters to doGet
Input is from the HttpServletRequest parameter Output is via the HttpServletResponse object, which we have named response
I/O in Java is very flexible but also quite complex, so this object acts as an assistant
79
The second parameter to doGet (or doPost) is HttpServletResponse response Everything sent via the Web has a MIME type The first thing we must do with response is set the MIME type of our reply: response.setContentType("text/html");
Because we will be outputting character data, we need a PrintWriter, handily provided for us by the getWriter method of response: PrintWriter out = response.getWriter(); Now were ready to create the actual page to be 80 returned
From here on, its just a matter of using our PrintWriter, named out, to produce the Web page First we create a header string:
String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; This line is technically required by the HTML spec Browsers mostly dont care, but HTML validators do care
81
Input to a servlet
A GET request supplies parameters in the form URL?name=value&name=value&name=value Actual spaces in the parameter values are encoded by + signs Other special characters are encoded in hex; for example, an ampersand is represented by %26 Parameter names can occur more than once, with different values A POST request supplies parameters in the same syntax, only it is in the body section of the request and is therefore harder for the user to see
82
Input parameters are retrieved via messages to the HttpServletRequest object request
Most of the interesting methods are inherited from the superinterface ServletRequest Returns an Enumeration of the parameter names If no parameters, returns an empty Enumeration Returns the value of the parameter name as a String If the parameter doesnt exist, returns null If name has multiple values, only the first is returned Returns an array of values of the parameter name If the parameter doesnt exist, returns null
All parameter values are retrieved as Strings Frequently these Strings represent numbers, and you want the numeric value int n = new Integer(param).intValue(); double d = new Double(param).doubleValue(); byte b = new Byte(param).byteValue(); Similarly for short, float, and long These can all throw a NumberFormatException, which is a subclass of RuntimeException boolean p = new Boolean(param).booleanValue(); char c = param.charAt(0);
85
form.html Example
<HTML> <HEAD> <TITLE>Introductions</TITLE> </HEAD> <BODY> <FORM METHOD=GET ACTION="http://localhost:8080/examples/servlet/Hello"> If you don't mind me asking, what is your name? <INPUT TYPE=TEXT NAME="name"><P> <INPUT TYPE=SUBMIT> </FORM> </BODY> </HTML>
form.html
86
Hello.java Example
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Hello extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); String name = req.getParameter("name"); out.println("<HTML>"); out.println("<HEAD><TITLE>Hello, " + name + "</TITLE></HEAD>"); out.println("<BODY>"); out.println("Hello, " + name); out.println("</BODY></HTML>");
87
<body> <h1>Forms Example Using Servlets</h1> <form action=http://localhost:8080/examples/servlet/EmailServl et> Enter your email ID: <input type=text name=email> <input type=submit> </form> </body> </html>
form2.html
88
EmailServlet.java
C:\j2sdk1.4.2_13\bin\CurrencyConvertor.java
90
Form3.html
91
ColorPostServlet.java
92
Using Cookies
93
Cookie
What is a cookie? A cookie is a piece of textual information Send by the Web server to the client browser Every time the browser visits the Web site again, the cookie is sent unchanged back to the server
94
Cookie
A cookie is a string upto 4K characters that you tell the Web browser to store on a visitors hard drive. Cookies give you a way to store information about the site visitor that can retrieve each time the visitor returns to the site so long as the visitor uses the same Web browser and computer system. Each Web browser type stores all cookie data in a single file unique to the browser.
Without cookies there is no way of determining what happened the last time the visitor came to the site or even if the visitor has ever been to your site before.
95
Benefits of Cookies
Identification of a user
E-commerce Poll Portals Personal Views Useful for sites that dont require high security
Customizing a site
Avoiding login
96
Drawbacks of Cookies
User can deny cookies in his Web browser Might be a privacy thread
97
99
100
Session Tracking
101
Session Tracking
HTTP is a stateless protocol. Each request is independent of the previous one. However, in some applications, it is necessary to save state information so that information can be collected from several interactions between a browser and a server. Sessions provide such a mechanism. Session state is shared among all the servlets that are associated with a particular client.
102
Procedure
A session can be created via the getSession( ) method of HttpServletRequest. An HttpSession object is returned. This object can store a set of bindings that associate names with objects. The
103
DateServlet.java
import import import import java.io.*; java.util.*; javax.servlet.*; javax.servlet.http.*;
When you first request this servlet, the browser displays one line with the current date and time information. On subsequent invocations, two lines are displayed. The first line shows the date and time when the servlet was last accessed. The second line shows the current date and time.
public class DateServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the HttpSession object. HttpSession hs = request.getSession(true); // Get writer. response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.print("<B>"); // Display date/time of last access. Date date = (Date)hs.getAttribute("date"); if(date != null) { pw.print("Last access: " + date + "<br>"); } // Display current date/time. date = new Date(); hs.setAttribute("date", date); pw.println("Current date: " + date); } } C:\j2sdk1.4.2_13\bin\DateServlet.java
104
Explaination of DateServlet.java
The getSession( ) method gets the current session. A new session is created if one does not already exist. The getAttribute( ) method is called to obtain the object that is bound to the name date.
That object is a Date object that encapsulates the date and time when this page was last accessed. (Of course, there is no such binding when the page is first accessed.)
A Date object encapsulating the current date and time is then created. The setAttribute( ) method is called to bind the name date to this object.
105