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).
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章