1 java servlets l servlets : programs that run within the context of a server, analogous to applets...

13
1 Java Servlets Java Servlets Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. Used to implement a service easily and efficiently. Easily: programmer may take advantage of support provided by Java Web Server: parsing HTTP requests handling connections to Web clients. Efficiently, run as separate light weight threads of the Java Server process rather than separate heavy weight processes load and execute much faster than CGI programs. 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.

Upload: rodney-nash

Post on 18-Jan-2016

212 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 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

1

Java ServletsJava Servlets Servlets : programs that run within the context of a server,

analogous to applets that run within the context of a browser. Used to implement a service easily and efficiently.

– Easily: programmer may take advantage of support provided by Java Web Server:

parsing HTTP requests handling connections to Web clients.

– Efficiently, run as separate light weight threads of the Java Server process rather than separate heavy weight processes

load and execute much faster than CGI programs.

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.

Page 2: 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

2

ServletsServlets 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

Page 3: 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

3

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

Servlet1 Servlet2

Page 4: 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

4

Life CycleLife Cycle A servlet is accessed through a URL, just as if it were a file or a

CGI program. When a request for a particular servlet is received, the Java Server

invokes the servlet as a separate thread of execution. 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.

The servlet is then destroyed by the Java Server.

Page 5: 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

5

Servlet usesServlet uses can process data which was POSTed over HTTPS using an HTML

FORM, passing data such as a purchase order (with credit card data).

servlets handle multiple requests concurrently: requests can be synchronized with each other to support collaborative applications such as on-line conferencing.

servlet can forward requests other servers.

– balance load among several servers which mirror same content.

…..

– cgi servlet can handle cgi requests

– file loader servlet can handle file loading requests

– ...

Page 6: 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

6

Class HierarchyClass Hierarchy Servlets are implemented using the Java Servlet API. All servlets implement the Servlet interface.

– extend either the GenericServlet class, which implements the Servlet interface, or its subclass, HttpServlet.

2 packages: javax.servlet and javax.servlet.http. 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.

Create a servlet as an extension of HttpServlet (which is a subclass of GenericServlet, which implements Servlet interface).

Page 7: 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

7

The Basic Framework For a Servlet classThe 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 }}

Page 8: 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

8

Example 1 – Class SampleServletExample 1 – Class SampleServlet Refer to SampleServlet.java After being loaded, servlet life cycle includes three methods: init() - server activates servlet

– perform potentially costly (usually, I/O intensive) setup only once, rather than once per request.

initializing sessions with other network services or getting access to their persistent data (stored in a database or file).

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.

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.

Page 9: 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

9

HTTPServletRequest and HTTPServletResponse

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:

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.)

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.

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

Page 10: 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

10

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.

Closing the Writer or ServletOutputStream after you send the response allows the server to know when the response is complete.

ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.

Page 11: 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

11

Servlet ModelServlet Model Servlets are java objects, so they:

Have instance-specific data

Encapsulate user sessions

– each servlet instantiated inside server is a separate entity

Can access environment through servletcontext object

– allow inter-servlet sharing of data

Page 12: 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

12

The service method is provided with Request and Response parameters.

– Servlets retrieve data through an input stream, and send responses using an output stream:

ServletInputStream in = request.getInputStream (); ServletOutputStream out = response.getOutputStream ();

Input and output streams may be used with data in whatever format is appropriate.

– object serialization

– HTML

– image formats

Page 13: 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

13

Example 2: Class VisitorInfoServletExample 2: Class VisitorInfoServlet Refer to VisitorInfoServlet.java