`
mabusyao
  • 浏览: 247296 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

Servlet Overview

    博客分类:
  • java
阅读更多

1 Servlet Overview

 

This chapter contains the following sections:


Note:

Sample servlet ap plications are included in the OC4J demos, available from the following location on the Oracle Technology Network (requiring an OTN membership, which is free of charge):
http://www.oracle.com/technology/tech/java/oc4j/demos/





<!-- class="inftblnote -->

Introduction to Servlets

The following sections offer a brief introduction to servlet technology:


No te:

The terms Web module and Web application are interchangeable in most uses and are both used throughout this document. If there is a distinction, it is that "Web module" typically indicates a single component, whether or not it composes an independent application, while "Web application" typically indicates a working application that may consist of multiple modules or components.

<!-- class="inftblnote -->

Review of Servlet Technology

In recent years, servlet technology has emerged as a powerful way to extend Web server functionality through dynamic Web pages. A servlet is a Java program that runs in a Web server, as opposed to an applet that runs in a client browser. Typically, the servlet takes an HTTP request from a browser, generates dynamic content (such as by querying a database), and provides an HTTP response back to the browser. Alternatively, the servlet can be accessed directly from another application component or send its output to another component. Most servlets generate HTML text, but a servlet may instead generate XML to encapsulate data.

More specifically, a servlet runs in a J2EE application server, such as OC4J. Servlets are one of the main application component types of a J2EE application, along with JavaServer Pages (JSP) and EJB modules, which are also server-side J2EE component types. These are used in conjunction with client-side components such as applets (part of the Java 2 Platform, Standard Edition specification) and application client programs. An application may consist of any number of any of these components.

Prior to servlets, Common Gateway Interface (CGI) technology was used for dynamic content, with CGI programs being written in languages such as Perl and being called by a Web application through the Web server. CGI ultimately proved less than ideal, however, due to its architecture and scalability limitations.

<!-- class="sect2" -->

Advantages of Servlets

In the Java realm, servlet technology offers advantages over applet technology for server-intensive applications, such as those accessing a database. One advantage of running in the server is that the server is usually a robust machine with many resources, making the program more scalable. Running in the server also results in more direct access to the data. The Web server in which a servlet is running is on the same side of the network firewall as the data being accessed.

Servlet programming also offers advantages over earlier models of server-side Web application development, including the following:

  • Servlets outperform earlier technologies for generating dynamic HTML, such as server-side "includes" or CGI scripts. After a servlet is loaded into memory, it can run on a single lightweight thread; CGI scripts must be loaded in a different process for every request.

  • Servlet technology, in addition to improved scalability, offers the well-known Java advantages of security, robustness, object orientation, and platform independence.

  • Servlets are fully integrated with the Java language and its standard APIs, such as JDBC for Java database connectivity.

  • Serv lets are fully integrated into the J2EE framework, which provides an extensive set of services that your Web application can use, such as Java Naming and Directory Interface (JNDI) for component naming and lookup, Java Transaction API (JTA) for managing transactions, Java Authentication and Authorization Service (JAAS) for security, Remote Method Invocation (RMI) for distributed applications, and Java Message Service (JMS). The following Web site contains information about the J2EE framework and services:

    http://java.sun.com/j2ee/docs.html
    
    
    
    
    
    
  • A servlet handles concurrent requests (through either a single servlet instance or multiple servlet instances, depending on the thread model), and servlets have a well-defined lifecycle. In addition, servlets can optionally be loaded when OC4J starts, so that any initialization is handled in advance instead of at the first user request. See "Servlet Preloading" .

  • The servlet request and response objects offer a convenient way to handle HTTP requests and send text and data back to the client.

Because servlets are written in the Java programming language, they are supported on any platform that has a Java virtual machine (JVM) and a Web server that supports servlets. Servlets can be used on different platforms without recompiling. You can package servlets together with associated files such as graphics, sounds, and other data to make a complete Web application. This simplifies application development and deployment.

In addition, you can port a servlet-based application from another Web server to OC4J with little effort. If your application was developed for a J2EE-compliant Web server, then the porting effort is minimal.

<!-- class="sect2" -->

The Ser vlet Interface and Request and Response Objects

A Java servlet, by definition, implements the javax.servlet.Servlet interface. This interface specifies methods to initialize a servlet, process requests, get the configuration and other basic information of a servlet, and terminate a servlet instance.

For Web applications, you can implement the Servlet interface by extending the javax.servlet.http.HttpServlet abstract class. (Alternatively, for protocol-independent servlets, you can extend the javax.servlet.GenericServlet class.) The HttpServlet class includes the following methods:

  • init(...) : Initialize the servlet.

  • destroy(...) : Terminate the servlet.

  • doGet(...) : Execute an HTTP GET request.

  • doPost(...) : Execute an HTTP POST request.

  • doPut(...) : Execute an HTTP PUT request.

  • doDelete(...) : Execute an HTTP DELETE request.

  • service(...) : Receive HTTP requests and, by default, dispatch them to the appropriate do XXX () methods.

  • getServletInfo(...) : Retrieve information about the servlet.

A servlet class that extends HttpServlet implements some or all of these methods, as appropriate, overriding the original implementations as necessary to process the request and return the response as desired. For example, most servlets override the doGet() method, doPost() method, or both to process HTTP GET and POST requests.

Each method takes as input an HttpServletRequest instance (an instance of a class that implements the javax.servlet.http.HttpServletRequest interface) and an HttpServletResponse instance (an instance of a class that implements the javax.servlet.http.HttpServletResponse interface).

The HttpServletRequest instance provides information to the servlet regarding the HTTP request, such as request parameter names and values, the name of the remote host that made the request, and the name of the server that received the request. The HttpServletResponse instance provides HTTP-specific functionality in sending the response, such as specifying the content length and MIME type and providing the output stream.

<!-- class="sect2" -->

Servlets and the Ser vlet Container

Unlike a Java client program, a servlet has no static main() method. Therefore, a servlet must execute under the control of an external container.

Servlet containers , sometimes referred to as servlet engines , execute and manage servlets. The servlet container calls servlet methods and provides services that the servlet needs while executing. A servlet container is usually written in Java and is either part of a Web server (if the Web server is also written in Java) or is otherwise associated with and used by a Web server. OC4J includes a fully standards-compliant servlet container.

The servlet container provides the servlet with easy access to properties of the HTTP request, such as its headers and parameters. When a servlet is called, such as when it is specified by URL, the Web server passes the HTTP request to the servlet container. The container, in turn, passes the request to the servlet. In the course of managing a servlet, a servlet container performs the following tasks:

  • It creates an instance of the servlet and calls its init() method to initialize it.

  • It constructs a request object to pass to the servlet. The request includes, among other things:

    • Any HTTP headers from the client

    • Parameters and values passed from the client (for example, names and values of query strings in the URL)

    • The complete URI of the servlet request

  • It constructs a response object for the servlet.

  • It invokes the servlet service() method. Note that for HTTP servlets, the generic service method is usually overridden in the HttpServlet class. The service method dispatches requests to the servlet doGet() or doPost() methods, depending on the HTTP header in the request (GET or POST ).

  • It calls the destroy() method of the servlet to discard it, when appropriate, so that it can be garbage collected. (For performance reasons, it is typical for a servlet container to keep a servlet instance in memory for reuse, rather than destroying it each time it has finished its task. It would be destroyed only for infrequent events, such as Web server shutdown.)

Figure 1-1 shows how a servlet relates to the servlet container and to a client, such as a Web browser. When the Web listener is the Oracle HTTP Server (powered by Apache), the connection to the OC4J servlet container goes through the mo d_oc4j module. See the Oracle HTTP Server Administrator's Guide for details.

Figure 1-1 Servlets and the Servlet Container

Description of Figure 1-1  follows
Description of "Figure 1-1 Servlets and the Servlet Container"

<!-- class="figure" -->
<!-- class="sect2" -->

Introduction to Serv let Sessions

Servlets use HTTP sessions to keep track of which user each HTTP request comes from, so that a group of requests from a single user can be managed in a stateful way. Servlet session tracking is similar in nature to session tracking in previous technologies, such as CGI.

This section provides an introduction to servlet sessions. See "Servlet Sessions" for more information and examples.

Introduction to Ses sion Tracking

Servlets provide convenient ways to keep the client and a server session in synchronization, enabling stateful servlets to maintain session state on the server over the whole duration of a client browsing session.

OC4J supports the following session-tracking mechanisms. See "Session Tracking" for more information.

  • Coo kies

    The servlet container sends a cookie to the client, which returns the cookie to the server upon each HTTP request. This process associates the request with the session ID indicated by the cookie. This is the most frequently used mechanism and is supported by any servlet container that adheres to the servlet specification.

  • UR L rewriting

    Instead of using cookies, the servlet can call the encodeURL() method of the response object, or the encodeRedirectURL() method for redirects, to append a session ID to the URL path for each request. This process allows the request to be associated with the session. This is the most frequently used mechanism for situations in which clients do not accept cookies.

<!-- class="sect3" -->

Introduction to the HttpSes sion Interface

In the standard servlet API, each client session is represented by an instance of a class that implements the javax.servlet.http.HttpSession interface. Servlets can set and get information about the session in this HttpSession object, which must be of application-level scope.

A servlet uses the getSession() method of an HttpServletRequest object to retrieve or create an HttpSession object for the user. This method takes a boolean argument to specify whether a new session object should be created for the client if one does not already exist within the application.

See "Features of the HttpSession Interface" for more information.

<!-- class="sect3" -->
<!-- class="sect2" -->

Introduction to Ser vlet Contexts

A servlet context is used to maintain information for all instances of a Web application within any single JVM (that is, for all servlet and JSP page instances that are part of the Web application). There is one servlet context for each Web application running within a given JVM; this is always a one-to-one correspondence. You can think of a servlet context as a container for a specific application.

Servlet Context Basics

Any servlet context is an instance of a class that implements the javax.servlet.ServletContext interface, with such a class being provided with any Web server that supports servlets.

A ServletContext object provides information about the servlet environment (such as name of the server) and allows sharing of resources between servlets in the group, within any single JVM. (For servlet containers supporting multiple simultaneous JVMs, implementation of resource-sharing varies.)

A servlet context provides the scope for the running instances of the application. Through this mechanism, each application is loaded from a distinct classloader and its runtime objects are distinct from those of any other application. In particular, the ServletContext object is distinct for an application, much as each HttpSession object is distinct for each user of the application.

Beginning with version 2.2 of the servlet specification, most implementations can provide multiple servlet contexts within a single host, which is what allows each Web application to have its own servlet context. (Previous implementations usually provided only a single servlet context with any given host.)

<!-- class="sect3" -->

How to Obtain a Servlet Context

Use the getServletContext() method of a servlet configuration object to retrieve a servlet context. See "Introduction to Servlet Configuration Objects" .

<!-- class="sect3" -->

Servlet Context Methods

The ServletContext interface specifies methods that allow a servlet to communicate with the servlet container that runs it, which is one of the ways that the servlet can retrieve application-level environment and state information. Methods specified in ServletContext include those listed here. For complete information, refer to the Sun Microsystems Javadoc at the following location:

http://java.sun.com/products/servlet/2.3/javadoc/index.html





  • void setAttribute(String name, Object value)

    This method binds the specified object to the specified attribute name in the servlet context. Using attributes, a servlet container can give information to the servlet that is not otherwise provided through the ServletContext interface.


    Note :

    For a servlet context, setAttribute() is a local operation only. It is not intended to be distributed to other JVMs within a cluster. (This is in accordance with the servlet specification.)

    <!-- class="inftblnote -->
  • Object getAttribute(String name)

    This method returns the attribute with the given name, or null if there is no attribute by that name. The attribute is returned as a java.lang.Object instance.

  • java.util.Enumeration getAttributeNames()

    This method returns a java.util.Enumeration instance containing the names of all available attributes of the servlet context.

  • void removeAttribute(String attrname)

    This method removes the specified attribute from the servlet context.

  • String getInitParameter(String name)

    This method returns a string that indicates the value of the specified context-wide initialization parameter, or null if there is no parameter by that name. This allows access to configuration information that is useful to the Web application associated with this servlet context.

  • Enumeration getInitParameterNames()

    This method returns a java.util.Enumeration instance containing the names of the initialization parameters of the servlet context.

  • RequestDispatcher getNamedDispatcher(String name)

    This method returns a javax.servlet.RequestDispatcher instance that acts as a wrapper for the specified servlet.

  • RequestDispatcher getRequestDispatcher(String path)

    This method returns a javax.servlet.RequestDispatcher instance that acts as a wrapper for the resource located at the specified path.

  • String getRealPath(String path)

    This method returns the real path, as a string, for the specified virtual path.

  • URL getResource(String path)

    This method returns a java.net.URL instance with a URL to the resource that is mapped to the specified path.

  • String getServerInfo()

    This method returns the name and version of the servlet container.

  • String getServletContextName()

    This method returns the name of the Web application with which the servlet context is associated, according to the <display-name> element of the web.xml file.

<!-- class="sect3" -->
<!-- class="sect2" -->

Introduction to Ser vlet Configuration Objects

A servlet configuration object contains initialization and startup parameters for a servlet and is an instance of a class that implements the javax.servlet.ServletConfig interface. Such a class is provided with any J2EE-compliant Web server.

You can retrieve a servlet configuration object for a servlet by calling the getServletConfig() method of the servlet. This method is specified in the javax.servlet.Servlet interface, with a default implementation in the javax.servlet.http.HttpServlet class.

The ServletConfig interface specifies the following methods:

  • ServletContext getServletContext()

    Retrieve a servlet context for the application. See "Introduction to Servlet Contexts" .

  • String getServletName()

    Retrieve the name of the servlet.

  • Enumeration getInitParameterNames()

    Retrieve the names of the initialization parameters of the servlet, if any. The names are returned in a java.util.Enumeration instance of String objects. (The Enumeration instance is empty if there are no initialization parameters.)

  • String getInitParameter(String name)

    This returns a String object containing the value of the specified initialization parameter, or null if there is no parameter by that name.

<!-- class="sect2" -->

Introduction to Servlet Filt ers

Request objects (instances of a class that implements HttpServletRequest ) and response objects (instances of a class that implements HttpServletResponse ) are typically passed directly between the servlet container and a servlet.

The servlet specification, however, allows servlet filters , which are Java programs that execute on the server and can be interposed between the servlet (or group of servlets) and the servlet container for special request or response processing.

If there is a filter or a chain of filters to be invoked before the servlet, these are called by the container with the request and response objects as parameters. The filters pass these objects, perhaps modified, or alternatively create and pass new objects, to the next object in the chain using the doChain() method.

See "Servlet Filters" for more information.

<!-- class="sect2" -->

Introduction to Ev ent Listeners

The servlet specification adds the capability to track key events in your Web applications through event listeners . This functionality allows more efficient resource management and automated processing based on event status.

When creating listener classes, you can implement standard interfaces for servlet context lifecycle events, servlet context attribute changes, HTTP session lifecycle events, and HTTP session attribute changes. A listener class can implement one, some, or all of the interfaces as appropriate.

An event listener class is declared in the web.xml deployment descriptor and invoked and registered upon application startup. When an event occurs, the servlet container calls the appropriate listener method.

See "Event Listeners" for more information.

<!-- class="sect2" -->

JSP Pages and Other J2EE Component Types

In addition to servlets, an application may include other server-side components, such as JSP pages and EJBs. It is especially common for servlets to be used in combination with JSP pages in a Web application. Servlets are managed by the OC4J servlet container; EJBs are managed by the OC4J EJB container; and JSP pages are managed by the OC4J JSP container. These containers form the core of OC4J.

JSP pages also involve the servlet container, because the JSP container itself is a servlet and is therefore executed by the servlet container. The JSP container translates JSP pages into page implementation classes, which are executed by the JSP container and are also essentially servlets.


Note:

Wherever this manual mentions functionality that applies to servlets, you can assume it applies to JSP pages as well unless stated otherwise.

<!-- class="inftblnote -->

For more information about JSP pages and EJBs, see the following:

<!-- class="sect2" -->

<!-- class="sect1" -->

A First Se rvlet Example

Looking at a basic example is the best way to demonstrate the general framework for writing a servlet.

Hello World Code

This servlet prints "Hi There!" back to the client. The comments note some of the basic aspects of writing a servlet.

// You must import at least the following packages for any servlet you write.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet, the base servlet implementation.
public class HelloServlet extends HttpServlet { 

  // Override the base implementation of doGet(), as desired.
  public void doGet (HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException { 
    // Set the MIME type for the response content.
    resp.setContentType("text/html"); 

    // Get an output stream to use in sending the output to the client.
    ServletOutputStream out = resp.getOutputStream(); 
    // Put together the HTML code for the output.
    out.println("<html>"); 
    out.println("<head><title>Hello World</title></head>");
    out.println("<body>");
    out.println("<h1>Hi There!</h1>");
    out.println("</body></html>");
  }
}

<!-- class="sect2" -->

Compiling and Deploying the Servlet

To try out the sample servlet code in an OC4J standalone environment, save it as HelloServlet.java in the /WEB-INF/classes directory of the OC4J default Web application. (See "OC4J Default Application and Default Web Application" .)

Next, compile the servlet. First verify that servlet.jar , supplied with OC4J, is in your classpath. This contains the Sun Microsystems javax.servlet and javax.servlet.http packages.


Note:

For convenience during development and testing, use the OC4J auto-compile feature for servlet code. This is enabled through the setting development="true" in the <orion-web-app> element of the global-web-application.xml file in the OC4J configuration files directory. The source-directory attribute may also have to be set appropriately. With auto-compile enabled, after you change the servlet source and save it in the appropriate directory, the OC4J server automatically compiles and redeploys the servlet the next time it is invoked.

See "Element Descriptions for global-web-application.xml and orion-web.xml" for more information about development and source-directory .


<!-- class="inftblnote -->

<!-- class="sect2" -->

Running the Servlet

Assuming that the OC4J server is up and running and that invocation by class name is enabled with the servlet-webdir built-in default setting of "/servlet/ ", you can invoke the servlet and see its output from a Web browser as follows, where host is the name of the host that the OC4J server is running on and port is the Web listener port:

http://host

:port

/servlet/HelloServlet

(See "Servlet Invocation by Class Name During OC4J Development" for information about invocation by class name and about the OC4J servlet-webdir attribute.)

In an OC4J standalone environment, use port 8888 to access the OC4J Web listener directly. (See "OC4J Standalone for Development" for an overview.)

This example assumes that "/ " is the context path of the Web application, as is true by default in OC4J standalone for the default Web application.

分享到:
评论

相关推荐

    An Overview of Servlet and JSP Technology.zip

    Abstract: Servlet program running in the server-side, dynamically generated Web page with the traditional CGI and many other similar compared to CGI technology, Java Servlet with a more efficient, ...

    servlet2.4doc

    Overview Package Class Tree Deprecated Index Help PREV NEXT FRAMES NO FRAMES A B C D E F G H I J L P R S U V -------------------------------------------------------------------------------- A ...

    4_1 An Overview of Servlet and JSP.ppt

    JSP相关资料

    4_1 An Overview of Servlet and JSP (1).ppt

    JSP相关资料

    servlet.chm

    帮助文档,We start with an overview of how and where servlets fit into the enterprise

    Overview-and-Setup-Chinese.pdf

    这一套教程对于初学者特别有用,我很久以前就收集了,希望对大家有帮助,我没有要积分下载,方便部分朋友,这些概念特别的重要,good good study ,day day up

    Servlet与JSP核心编程第二版.pdf

    01-Overview-and-Setup-Chinese.pdf 02-Servlet-Basics-Chinese.pdf 03-Form-Data-Chinese.pdf 04-Request-Headers-Chinese.pdf 05-Status-Codes-Chinese.pdf 06-Response-Headers-Chinese.pdf 07-Cookies-Chinese....

    Tomcat The Definitive Guide, 2nd Edition(PDF)

    It takes a book as versatile as its subject to cover Apache Tomcat, the popular open source Servlet and JSP container and high performance web server. Tomcat: The Definitive Guide is a valuable ...

    The Java EE 6 Tutorial Basic Concepts 4th Edition

    Chapter 1: Overview 3 Java EE 6 Platform Highlights 4 Java EE Application Model 5 Distributed Multitiered Applications 6 Java EE Containers 13 Web Services Support 15 Java EE Application ...

    java视频教程Day01 免费

    14. JDBC Overview and Using JDBC (JDBC概述及使用) 15. JDBC 2.0 core features (JDBC 2.0核心) 16. JDBC 2.0 standard extension (JDBC 2.0高级特性) 以上教学过程中将讲一个使用Java编写暴力破解数据库...

    java_webcrawler:XPath 引擎、网络爬虫和爬虫的网络界面。 专为 CIS 555(互联网和网络系统)构建

    ##Overview## edu/upenn/cis455包含网络爬虫、XPath 引擎和爬虫接口。 test/edu/upenn/cis455包含这些程序的测试。 ###Implementation### 在edu/upenn/cis455有四个目录: crawler 、 servlet 、 storage和...

    tomcat-7.0.90-developer.zip

    The Apache Tomcat® software is an open source implementation of the Java Servlet, JavaServer Pages, Java Expression Language and ...[Java Community Process](https://jcp.org/en/introduction/overview).

    tomcat-7.0.90-windows-x64.zip

    The Apache Tomcat® software is an open source implementation of the Java Servlet, JavaServer Pages, Java Expression Language and ...[Java Community Process](https://jcp.org/en/introduction/overview).

    Java常用工具包Jodd.zip

    获取函数参数名jodd-dboom 数据库访问的轻量级封装,可看作一个简单的ORMjodd-json JSON解析、序列化jodd-vtor 一个基于注解的字段验证框架了解更多: GitHub page (5 min overview): http://oblac.github.io/jodd...

    外文翻译 stus MVC

    ActionServlet is the Command part of the MVC implementation and is the core of the Framework. ActionServlet (Command) creates and uses Action, an ActionForm, and ActionForward. As mentioned earlier, ...

    Apache-Solr-Reference-Guide-v3.5

    describes running Solr in the Apache Tomcat servlet runner and Web server. Other topics include how to back up a Solr instance, and how to run Solr with Java Management Extensions (JMX). : This ...

    hibernate+中文api

    1.4.1. 编写基本的servlet 1.4.2. 处理与渲染 1.4.3. 部署与测试 1.5. 总结 2. 体系结构(Architecture) 2.1. 概况(Overview) 2.2. 实例状态 2.3. JMX整合 2.4. 对JCA的支持 2.5. 上下文相关的(Contextual...

    Spring.Boot.Cookbook.1785284150

    The book starts with an overview of the important and useful Spring Boot starters that are included in the framework, and teaches you to create and add custom Servlet Filters, Interceptors, Converters...

    ssh(structs,spring,hibernate)框架中的上传下载

    Struts+Spring+Hibernate实现上传下载    本文将围绕SSH文件上传下载的主题,向您详细讲述如何开发基于SSH的Web程序。SSH各框架的均为当前最新版本:  •Struts 1.2  •Spring 1.2.5  •Hibernate 3.0 ...

Global site tag (gtag.js) - Google Analytics