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

JavaEETutorial5概译------Chapter 4 (一)

阅读更多
Java Servlet Technology

What Is a Servlet?
    Servlet是一个Java类,它被用来为服务器增加一个 请求-相应模式 的能力。虽然Servlet可以接受任何类型的请求,但是一般servlet用在web服务器上。所以一般使用Http请求。
    javax.servlet 和 javax.servlet.http是相关的接口,任何servlet都需要实现Servlet 接口。当你想写一个通用的servlet的时候可以继承GenericServlet,而如果你想写一个http servlet那么可以继承HttpServlet。

The Example Servlets
    主要讲解了一个例子。重点应该就是里面对DD的讲解。
    *<display-name>元素是唯一标示应用的,供工具使用
      A display-name element that specifies the name that tools use to identify the application.
    *一系列的<filter>元素是用来定义servlet的过滤器的。
      A set of filter elements that identify servlet filters contained in the application.
    *<filter-mapping>元素则是和<filter>元素对应的,过滤那些需要过滤的servlet的请求或响应。一个<filter-mapping>可映射多个servlet mapping和多个URL到一个特定的filter上。
      A set of filter-mapping elements that identify which servlets will have their requests or responses filtered by the filters identified by the filter elements. A filter-mapping element can define more than one servlet mapping and more than one URL pattern for a particular filter.
    *一系列<servlet>元素定义了所有的servlet实例。
      A set of servlet elements that identify all the servlet instances of the application.
    *一系列的<servlet-mapping>元素将servlet映射到URL上。一个servlet可匹配多个URL
      A set of servlet-mapping elements that map the servlets to URL patterns. More than one URL pattern can be defined for a particular servlet.
    *一系列的<error-page>映射异常到一个HTML页面,所以此页面在异常被抛出时被打开。
      A set of error-page mappings that map exception types to an HTML page, so that the HTML page opens when an exception of that type is thrown by the application.

Servlet Life Cycle

    servlet被部署后,其生命周期将由容器控制。当一个请求请求一个servlet的时候,容器以下面的步骤执行。
#如果还没有servlet实例,那么容器将会:
   1.加载servlet类
   2.创建一个servlet实例
   3.调用servlet的init方法来初始化servlet实例。
#执行service方法,传递请求和相应对象。

Handling Servlet Life-Cycle Events

    通过定义监听器对象,可以在servlet的生命周期内对其事件进行监听或这对这些事件做出响应。

Defining the Listener Class

    监听器类需要实现listener接口。下面是监听器及相应的事件。



    下面是例子代码。此代码是从ServletContextEvent中取得web上下文对象,然后将需要的对象作为属性存到上下文对象中。

import database.BookDBAO;
import javax.servlet.*;
import util.Counter;

import javax.ejb.*;
import javax.persistence.*;

public final class ContextListener
    implements ServletContextListener {
    private ServletContext context = null;

    @PersistenceUnit
    EntityManagerFactory emf;

    public void contextInitialized(ServletContextEvent event) {
        context = event.getServletContext();
        try {
            BookDBAO bookDB = new BookDBAO(emf);
            context.setAttribute("bookDB", bookDB);
        } catch (Exception ex) {
            System.out.println(
                "Couldn’t create database: " + ex.getMessage());
        }
        Counter counter = new Counter();
        context.setAttribute("hitCounter", counter);
        counter = new Counter();
        context.setAttribute("orderCounter", counter);
    }

    public void contextDestroyed(ServletContextEvent event) {
        context = event.getServletContext();
        BookDBAO bookDB = context.getAttribute("bookDB");
        bookDB.remove();
        context.removeAttribute("bookDB");
        context.removeAttribute("hitCounter");
        context.removeAttribute("orderCounter");
    }
}


Using Scope Objects
    servlet可以使用下面四个scope objects。



Controlling Concurrent Access to Shared Resources


并发在下面几种情况下发生的几率比较大

    *多个web组件访问web上下文中的对象
      Multiple web components accessing objects stored in the web context.
    *多个web组件访问session中的对象
      Multiple web components accessing objects stored in a session.
    *一个web组件的多个线程访问一个实例变量。web容器会为每个请求创建一个线程。如果你想要保证servlet实例每次只处理一个请求,那么servlet可以实现SingleThreadModel接口。如果servlet实现了此几口,你就能保证不会有两个线程同时调用servlet的service方法。
      Multiple threads within a web component accessing instance variables. A web container will typically create a thread to handle each request. If you want to ensure that a servlet instance handles only one request at a time, a servlet can implement the SingleThreadModel interface. If a servlet implements this interface, you are guaranteed that no two threads will execute concurrently in the servlet’s service method. A web container can implement this guarantee by synchronizing access to a single instance of the servlet, or by maintaining a pool of web component instances and dispatching each new request to a free instance. This interface does not prevent synchronization problems that result from web components accessing shared resources such as static class variables or external objects. In addition, the Servlet 2.4 specification deprecates the SingleThreadModel interface.

Initializing a Servlet
    web容器加载了servlet后,将会初始化servlet。想要自定义初始化时的动作,覆盖init方法即可。


Writing Service Methods
    servlet主要是通过定义在GenericServlet里的service方法来提供服务的。
    对于HTTP servlet来说,正确的组建一个响应的顺序是先从response里面取到输出流,然后向输出流中填入响应头和内容。响应头必须在响应被提交前写入,否则将被忽略。

Getting Information from Requests
    请求在客户端和servlet之间传送数据。所有的请求都实现了ServletRequest接口。这个接口定义了接收如下信息的方法:
    *参数,这是用来在客户端和servlet之间传送数据的。
      Parameters, which are typically used to convey information between clients and servlets
    *对象值属性,这是用来在servlet容器和servlet或者servlet之间传送信息的。
      Object-valued attributes, which are typically used to pass information between the servlet container and a servlet or between collaborating servlets
    *关于请求协议的信息以及客户端和服务器端在请求中被执行的信息。
      Information about the protocol used to communicate the request and about the client and server involved in the request
    *关于地址的信息
      Information relevant to localization

    请求URL形式如下:
    http://[host]:[port][request-path]?[query-string]

    请求路径还由下面内容组成:
    *上下文路径:由/+应用的根路径组成。
      Context path: A concatenation of a forward slash (/) with the context root of the servlet’s web application.
    *serlvet路径:由/+form里面的action组成。
      Servlet path: The path section that corresponds to the component alias that activated this request. This path starts with a forward slash (/).
    *路径信息:这部分的请求路径不是上下文路径或servlet路径中的一部分。
      Path info: The part of the request path that is not part of the context path or the servlet path.

Constructing Responses
    相应和请求对应,是从服务器端想客户端发送数据的。需要实现ServletResponse接口,其提供的方法允许你做如下操作:
    *获得向客户端发送数据的输出流。....
      Retrieve an output stream to use to send data to the client. To send character data, use the PrintWriter returned by the response’s getWriter method. To send binary data in a MIME body response, use the ServletOutputStream returned by getOutputStream. To mix binary and text data (as in a multipart response), use a ServletOutputStream and manage the character sections manually.
    *setContentType方法能设置返回内容的格式。此方法必须在响应提交前调用。
      Indicate the content type (for example, text/html) being returned by the response with the setContentType(String) method. This method must be called before the response is committed. A registry of content type names is kept by the Internet Assigned Numbers Authority (IANA) at http://www.iana.org/assignments/media-types/.
    *setBufferSize设置是否需要缓存。默认情况是响应一提交就发送。
      Indicate whether to buffer output with the setBufferSize(int) method. By default, any content written to the output stream is immediately sent to the client. Buffering allows content to be written before anything is actually sent back to the client, thus providing the servlet with more time to set appropriate status codes and headers or forward to another web resource. The method must be called before any content is written or before the response is committed.
    *设置路径信息。
      Set localization information such as locale and character encoding. See Chapter 15, Internationalizing and Localizing Web Applications for details.

    HTTP响应对象有如下字段在HTTP头中使用:
    *状态码,用来表示一个请求是否符合要求或者请求是否已经重定向。
      Status codes, which are used to indicate the reason a request is not satisfied or that a request has been redirected.
    *cookie,用来在客户端保存一些应用的特殊信息。
      Cookies, which are used to store application-specific information at the client. Sometimes cookies are used to maintain an identifier for tracking a user’s session (see Session Tracking).
  • 大小: 50.6 KB
  • 大小: 30 KB
4
0
分享到:
评论

相关推荐

    javaeetutorial5-master.zip

    "javaeetutorial5-master.zip" 是一个包含Java EE 5官方教程示例代码的压缩包。由于官网上的资源已经失效,这个压缩包对于学习和理解Java EE 5的核心概念和技术非常宝贵。下面将详细介绍这个压缩包中可能包含的一些...

    javaeetutorial5part1

    javaeetutorial5

    JavaEETutorial5(含源码)

    sun网站下的,方便上不了国外网站的朋友,内容详细,讲解透彻。

    javaeetutorial5.part2

    javaeetutorial5

    javaeetutorial5.part3

    javaeetutorial5

    JavaEETutorial

    Java EE是一个用于构建大型、分布式、企业级应用的框架,它提供了丰富的服务和组件,如Servlet、JSP、EJB、JMS、JPA、JAX-RS等,来简化开发复杂系统的流程。 Java EE的核心概念之一是分层架构,它将应用分为表现层...

    javaeetutorial5.rar

    The aim of the Java EE 5 platform is to provide developers a powerful set of APIs while reducing development time, reducing application complexity, and improving application performance.

    javaEE指南+向导6-javaeetutorial6.rar

    这个压缩包包含了一份PDF文档,即"6-javaeetutorial6.pdf",该文档通常包含了对Java EE 6的全面介绍,涵盖了各种关键组件和服务。 Java EE 6是一个用于构建企业级分布式应用的框架,它提供了一整套服务和API,包括...

    javaeetutorial7.pdf

    根据给定的文件信息,文件名为"javaeetutorial7.pdf",描述为"JavaEE7的官方教程,英文原版,适合有一定英文阅读能力的读者",标签为"javaee7 tutorial7"。从这些信息中,我们可以得知知识点主要围绕Java EE 7 (Java...

    JavaEETutorial1.5.pdf

    Java Platform, Enterprise Edition (Java EE) 5 是一个企业级应用开发平台的标准版,它为开发者提供了构建可伸缩、可移植、健壮的应用程序所需的一组规范和技术。Java EE 5相比之前的版本进行了重大的改进和增强,...

    Java EE 7 Tutorial: The Duke's Bookstore

    5. **EJB(Enterprise JavaBeans)**:EJB是Java EE中的核心组件,提供了一种标准的方式来实现业务逻辑。在Duke's Bookstore,EJB可能被用来封装复杂的业务规则,如库存管理、订单处理和支付验证。 6. **JAX-RS...

    JavaEETutorial.pdf

    Java Platform, Enterprise Edition (Java EE) 5 是一个用于开发企业级应用程序的标准平台。它由一系列规范组成,旨在提供一套全面的技术栈来支持复杂的企业应用开发。Java EE 5 版本发布于2006年,是Java EE发展...

    JavaEE Tutorial

    JavaEE(Java Platform, Enterprise Edition)是Oracle公司提供的一个企业级应用开发平台,它扩展了Java SE(标准版)的功能,主要用于构建分布式、多层架构的企业级应用程序。本教程将深入探讨JavaEE的核心概念和...

    javaeetutorial7

    4. 上下文和依赖注入(Contexts and Dependency Injection):Java EE 7引入了CDI(Contexts and Dependency Injection),这是一种帮助开发者在Java EE应用程序中管理依赖关系和生命周期的框架。 5. Bean 验证...

    javaeetutorial7(官方文档)

    Java EE 7(Java Platform, Enterprise Edition 7)是Java企业级开发的一个重要版本,由Oracle公司于2013年发布。该版本引入了许多新特性,旨在简化企业应用的开发与部署流程,并提高应用程序的性能和可维护性。...

    javaeetutorial6

    《Java EE 6 教程》(The Java EE 6 Tutorial)是一份由甲骨文公司(Oracle)出版的专业文档,旨在为开发者提供关于Java平台企业版(Java Platform, Enterprise Edition, 简称Java EE)应用程序开发的指导。...

Global site tag (gtag.js) - Google Analytics