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

[b]Java Servlet Technology[/b]

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

[b]The Example Servlets[/b]
主要讲解了一个例子。重点应该就是里面对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.

[b]Servlet Life Cycle[/b]

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

[b]Handling Servlet Life-Cycle Events[/b]

通过定义监听器对象,可以在servlet的生命周期内对其事件进行监听或这对这些事件做出响应。
[b]
Defining the Listener Class[/b]
监听器类需要实现listener接口。下面是监听器及相应的事件。

[img]/upload/attachment/80142/73c4b202-b62d-3f77-abbd-644c734e1916.jpg[/img]

下面是例子代码。此代码是从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");
}
}


[b]Using Scope Objects[/b]
servlet可以使用下面四个scope objects。

[img]/upload/attachment/80156/d981611a-2112-39a7-8ef0-833f18299114.jpg[/img]
[b]
Controlling Concurrent Access to Shared Resources[/b]

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

*多个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.

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


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

[b]Getting Information from Requests[/b]
请求在客户端和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.

[b]Constructing Responses[/b]
相应和请求对应,是从服务器端想客户端发送数据的。需要实现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).
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章