Top Banner
Introduction to Web Containers Mohan Bang
40
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Servlet

Introduction to Web Containers

Mohan Bang

Page 2: Servlet

• Application Clients

• Web Clients– A Web Browser– HTML and others for User Interface– HTTP(S)

Page 3: Servlet

The HTTP Protocol

• Hyper Text Transfer Protocol (HTTP), the actual communications protocol that enables Web browsing.

• The Hypertext Transfer Protocol is the set of rules for exchanging files (text, graphic images, sound, video, and other multimedia files) on the World Wide Web.

• It is a stateless protocol based on requests and response.

Page 4: Servlet

• The GET Request Method

• The POST Request Method

• The HEAD Request Method

• The HTTP Response

HTTP Requests Methods

Page 5: Servlet

• The GET Request Method

The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process.

Page 6: Servlet

• The POST Request Method

• The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions:

• - Annotation of existing resources; - Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles; - Providing a block of data, such as the result of submitting a form, to a data-handling process; - Extending a database through an append operation. The actual function performed by the POST method is determined by the server and is usually dependent on the Request-URI. The posted entity is subordinate to that URI in the same way that a file is subordinate to a directory containing it, a news article is subordinate to a newsgroup to which it is posted, or a record is subordinate to a database.

Page 7: Servlet

Web Applications

Web Applications are server-side applications. The most essential requirements for server side application developments are:

• A programming model and an API

• Server-side runtime support

• Deployment support

Page 8: Servlet

• To meet these requirements when building and running web applications, the J2EE, specification provides the following

• Java Servlets and JavaServer Pages

• Web Applications

• A Web Container

• A Packaging structure and deployment Descriptors

Page 9: Servlet

Deployment Descriptors

• Inilization of parameters for servlets and web applications

• Servlet/JSP Definitions

• Servlets/JSP Mappings

• MIME Type

• Security

Page 10: Servlet

Structure of WEB Application

Page 11: Servlet

– /WEB-INF/web.xml

– The Web Application deployment descriptor that configures the Web Application.

– /WEB-INF/classes

– Contains server-side classes such as HTTP servlets and utility classes.

– /WEB-INF/lib

– Contains .jar files used by the Web Application, including JSP tag libraries.

Page 12: Servlet

Servlets

Page 13: Servlet

As soon as the Web begin to be used for delivering services, service providers recognized the need for dynamic content. Applets, one of the earliest attempts towards this goal, focused on using the client platform to deliver dynamic user experiences. At the same time, developers also investigated using the server platform for this purpose. Initially, Common Gateway Interface (CGI) scripts were the main technology used to generate dynamic content. Though widely used, CGI scripting technology has a number of shortcomings, including platform dependence and lack of scalability. To address these limitations, Java Servlet technology was created as a portable way to provide dynamic, user-oriented content

Page 14: Servlet

What Is a Servlet?

A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed via a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.

Page 15: Servlet

The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods.

When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services

Page 16: Servlet

Advantage of Servlets Over "Traditional" CGI?

• Efficient. With traditional CGI, a new process is started for each HTTP request. If the CGI program does a relatively fast operation, the overhead of starting the process can dominate the execution time. With servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread, not a heavyweight operating system process. Similarly, in traditional CGI, if there are N simultaneous request to the same CGI program, then the code for the CGI program is loaded into memory N times. With servlets, however, there are N threads but only a single copy of the servlet class. Servlets also have more alternatives than do regular CGI programs for optimizations such as caching previous computations, keeping database connections open, and the like.

Page 17: Servlet

• Convenient. Hey, you already know Java. Why learn Perl too? Besides the convenience of being able to use a familiar language, servlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such utilities.

Page 18: Servlet

• Powerful. Java servlets let you easily do several things that are difficult or impossible with regular CGI. For one thing, servlets can talk directly to the Web server (regular CGI programs can't). This simplifies operations that need to look up images and other data stored in standard places. Servlets can also share data among each other, making useful things like database connection pools easy to implement. They can also maintain information from request to request, simplifying things like session tracking and caching of previous computations.

Page 19: Servlet

• Portable. Servlets are written in Java and follow a well-standardized API. Consequently, servlets written for, say I-Planet Enterprise Server can run virtually unchanged on Apache, Microsoft IIS, or WebStar. Servlets are supported directly or via a plugin on almost every major Web server.

Page 20: Servlet

• Inexpensive. There are a number of free or very inexpensive Web servers available that are good for "personal" use or low-volume Web sites. However, with the major exception of Apache, which is free, most commercial-quality Web servers are relatively expensive. Nevertheless, once you have a Web server, no matter the cost of that server, adding servlet support to it (if it doesn't come preconfigured to support servlets) is generally free or cheap.

Page 21: Servlet

Servlet-Capable Web Server

• Apache Tomcat.

• JavaServer Web Development Kit (JSWDK).

• Allaire JRun.

• New Atlanta’s ServletExec.

• Sun’s Java Web Server.

• JBoss

• Others

Page 22: Servlet

Basic Servlet Structure

Page 23: Servlet

import java.io.*; import javax.servlet.*; import javax.servlet.http.*;public class SomeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException { // Use "request" to read incoming HTTP headers (e.g. cookies)

// and HTML form data (e.g. data the user entered and submitted) // Use "response" to specify the HTTP response line and headers // (e.g. specifying the content type, setting cookies).

PrintWriter out = response.getWriter(); / / Use "out" to send content to browser

} }

Page 24: Servlet

import java.io.*; import javax.servlet.*;import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException

{ PrintWriter out = response.getWriter();

out.println("Hello World"); } }

Page 25: Servlet

Servlet Lifecycle

• Handled by the servlet container.

• Create and initialize the servlet.

• Handle zero or more service calls.

• Destroy and garbage collect the servlet.

• A single servlet instance to handle every request.

Page 26: Servlet

HTTPServlet

• Override doGet() to handle GET requests.

• Override doPost() to handle POST requests.

• Both methods take HTTPServletRequest and HTTPServletResponse as arguments.

• A few other methods, but used much less often - doDelete, doTrace, doOptions, doPut

Page 27: Servlet

HTTPServletRequest

• getMethod()

• getQueryString()

• getRemoteHost()

• getRemoteAddr()

• getAuthType()

• getContentType()

Page 28: Servlet

HTTPServletResponse

• getWriter()

• setContentType()

• getOutputStream()

Page 29: Servlet

Servlet Sessions, Context and

Collaboration

Page 30: Servlet

Requirements• Session

– The server should be able to identify that a series of requests from a single client form a single working ‘session’. By associating a specific request to belong to a specific working session.The Shopping cartThe Online Banking Application

• State– The server should be able to remember

information releated to previous requests.

Page 31: Servlet

Session Tracking

• URL Rewriting

• Hidden form fields

• Cookies

Page 32: Servlet

Servlet Collaboration

• Servlet Chaining

• Request Dispatching

Page 33: Servlet

Filters

Page 34: Servlet

• The Java Servlet specification version 2.3 introduces a new component type, called a filter. A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. Filters typically do not themselves create responses, but instead provide universal functions that can be "attached" to any type of servlet or JSP page.

• Filters are important for a number of reasons. First, they provide the ability to encapsulate recurring tasks in reusable units. Organized developers are constantly on the lookout for ways to modularize their code. Modular code is more manageable and documentable, is easier to debug, and if done well, can be reused in another setting.

Page 35: Servlet

• Second, filters can be used to transform the response from a servlet or a JSP page. A common task for the web application is to format data sent back to the client. Increasingly the clients require formats (for example, WML) other than just HTML. To accommodate these clients, there is usually a strong component of transformation or filtering in a fully featured web application. Many servlet and JSP containers have introduced proprietary filter mechanisms, resulting in a gain for the developer that deploys on that container, but reducing the reusability of such code. With the introduction of filters as part of the Java Servlet specification, developers now have the opportunity to write reusable transformation components that are portable across containers.

Page 36: Servlet

• Authentication-Blocking requests based on user identity.

• Logging and auditing-Tracking users of a web application.

• Image conversion-Scaling maps, and so on. • Data compression-Making downloads smaller. • Localization-Targeting the request and response to a

particular locale. • XSL/T transformations of XML content-Targeting

web application responses to more that one type of client.

• There are many more, such as encryption, tokenizing, triggering resource access events, mime-type chaining, and caching.

Page 37: Servlet

The Filter API

• javax.servlet.Filter

• javax.servlet.FilterConfig

• javax.servlet.FilterChain

Page 38: Servlet

Listeners

Page 39: Servlet

• A listener can be used to monitor and react to events on a servlet's life cycle by defining listener objects whose methods get invoked when life cycle events occur. Support for application level events is included in the Java Servlet Specification 2.3.

• Application event listeners are classes that implement one or more of the servlet event listener interfaces. Servlet event listeners support notification for state changes in the ServletContext and HttpSesion objects, specifically:

• Servlet context listeners are used to manage resources or state held at a VM level for the application.

• HTTP session listeners are used to manage state or resources associated with a series of requests made into a web application from the same client or user.

• You can have multiple listener classes listening to each event type and specify the order in which the container invokes the listener beans for each event type.

Page 40: Servlet

Listener Interface

Servlet Context Events

Lifecycle The Servlet context has just been created and is available to service its first request, or the Servlet context is about to be shutdown.

javax.Servlet.ServletContextListener

Changes to Attributes

Attributes on the Servlet context has been added, removed, or replaced.

javax.Servlet.ServletContextAttributesListener

Http Session Events

Lifecycle An HttpSession has just been created, or has been invalidated or timed out.

javax.Servlet.http.HttpSessionListener

Changes to Attributes

Attributes have been added, removed or replaced in an HttpSession object.

javax.Servlet.http.HttpSessionAttributesListener