1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to implement a service easily and efficiently. –Easily: programmer may take advantage of support provided by Java Web Server: l parsing HTTP requests l handling connections to Web clients. –Efficiently, run as separate light weight threads of the Java Server process rather than separate heavy weight processes l load and execute much faster than CGI programs. l Servlets are part of a larger Java Server Architecture. – first implemented in a server built by Sun that was called Jeeves, later renamed the Java Web Server java.sun.com/products/java_server/webserver.
2 Servlets l Servlets have several advantages: –Compiled –Crash-resistant –Capable of running in-process –Cross-platform –Durable –Dynamically loadable across the network –Extensible –Multi-threaded –Protocol independent –Secure –Written in Java
3 l Servlets are protocol- and platform-independent server-side components, written in Java, to dynamically extend Java-enabled servers. –run inside servers, don’t need a GUI. –downloaded on demand to system that requests them. Client 1 -Applet Client 2 -HTML form Java Server Call Servlet Servlet1Servlet2
4 Life Cycle l A servlet is accessed through a URL, just as if it were a file or a CGI program. l When a request for a particular servlet is received, the Java Server invokes the servlet as a separate thread of execution. l Once started, it can receive environment information as well as client query information similar to that provided through the CGI. It processes the request and returns its data, formatted as HTML, to be included in the body of the HTTP response generated by the Java Server. l The servlet is then destroyed by the Java Server.
5 Servlet uses l can process data which was POSTed over HTTPS using an HTML FORM, passing data such as a purchase order (with credit card data). l servlets handle multiple requests concurrently: requests can be synchronized with each other to support collaborative applications such as on-line conferencing. l servlet can forward requests other servers. – balance load among several servers which mirror same content. l ….. –cgi servlet can handle cgi requests –file loader servlet can handle file loading requests –...
6 Class Hierarchy l Servlets are implemented using the Java Servlet API. l All servlets implement the Servlet interface. –extend either the GenericServlet class, which implements the Servlet interface, or its subclass, HttpServlet. l 2 packages: javax.servlet and javax.servlet.http. l not part of the core Java framework, so do not begin with java. part of the Standard Java Extension API, begin with the keyword javax. l Create a servlet as an extension of HttpServlet (which is a subclass of GenericServlet, which implements Servlet interface).
7 The Basic Framework For a Servlet class Extend and use the default functionality of one of two servlet classes – GenericServlet or HTTPServlet. - Override at least one of the methods – init(), service(), doGet(), doPost(), doPut() to provide custom functionality. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; /** * A Basic Framework for a Servlet **/ public class FrameServlet extends HttpServlet { public void init() { // servlet initialization code goes here } public void service(){ //The custom code to offer the service goes here } public void destroy(){ // free resources here }
8 Example 1 – Class SampleServlet l Refer to SampleServlet.java l After being loaded, servlet life cycle includes three methods: l init() - server activates servlet –perform potentially costly (usually, I/O intensive) setup only once, rather than once per request. l initializing sessions with other network services or l getting access to their persistent data (stored in a database or file). l service() - servlet handles many requests. Each client request generates one service() call. –requests may be concurrent; allows servlets to coordinate activities among many clients. –Class-static state may be used to share data between requests. l destroy() - requests processed until servlet is explicitly shut down by the web server, by calling the destroy method. –Servlet's class may become eligible for garbage collection.
9 HTTPServletRequest and HTTPServletResponse l When a servlet accepts a call from a client, it receives two objects: –An object of type HTTPServletRequest, encapsulates communication from client to the server. –An HttpServletRequest object provides access to HTTP header data, such as any cookies found in the request and the HTTP method with which the request was made. –The HttpServletRequest object also allows you to obtain the arguments that the client sent as part of the request. To access client data: l The getParameter method returns the value of a named parameter. If your parameter could have more than one value, use getParameterValues instead. The getParameterValues method returns an array of values for the named parameter. (The method getParameterNames provides the names of the parameters.) l For HTTP GET requests, the getQueryString method returns a String of raw data from the client. You must parse this data yourself to obtain the parameters and values. l For HTTP POST, PUT, and DELETE requests, If you expect text data, the getReader method returns a BufferedReader for you to use to read the raw data. If you expect binary data, the getInputStream method returns a ServletInputStream for you to use to read the raw data –
10 l A HTTPServletResponse, encapsulates communication from servlet back to the client. –Allows servlet to set the content length and MIME type of the reply. –Provides an output stream, ServletOutputStream, and a Writer through which the servlet can send the reply data. –Use the getWriter method to return text data to the user, and the getOutputStream method for binary data. l Closing the Writer or ServletOutputStream after you send the response allows the server to know when the response is complete. l ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.
11 Servlet Model l Servlets are java objects, so they: l Have instance-specific data l Encapsulate user sessions –each servlet instantiated inside server is a separate entity l Can access environment through servletcontext object –allow inter-servlet sharing of data
12 l The service method is provided with Request and Response parameters. –Servlets retrieve data through an input stream, and send responses using an output stream: l ServletInputStream in = request.getInputStream (); l ServletOutputStream out = response.getOutputStream (); l Input and output streams may be used with data in whatever format is appropriate. –object serialization –HTML – image formats
13 Example 2: Class VisitorInfoServlet l Refer to VisitorInfoServlet.java