1. 程式人生 > >servlet,servlet容器

servlet,servlet容器

首先,得先大概知道web伺服器是什麼,接著,明白servlet的作用,以及為什麼要有servlet容器。最後,再深入瞭解servlet。

1. What is a web server?

To know what is a Servlet container, we need to know what is a Web Server first
為了知道servlet容器是什麼,我們首先得知道web伺服器是什麼。
A web server uses HTTP protocol to transfer data.
web伺服器使用HTTP協議傳輸資料。
In a simple situation, a user type in a URL (e.g. www.programcreek.com/static.html) in browser (a client), and get a web page to read.
在一個簡單的情形下,就是使用者在瀏覽器輸入一個URL,然後得到一個web頁面去閱讀。
So what the server does is sending a web page to the client. The transformation is in HTTP protocol which specifies the format of request and response message.
所以,一個伺服器做的事就是傳送網頁給客戶端。而傳輸是在HTTP寫一下進行的,這個協議明確了請求和響應資訊的格式。

2. What is a Servlet Container?

As we see here, the user/client can only request static webpage from the server. This is not good enough, if the user wants to read the web page based on his input.
我們已經看到,使用者只能從伺服器請求靜態頁面,但這是不夠好的,比如使用者想基於他的輸入來讀頁面時。
The basic idea of Servlet container is using Java to dynamically generate the web page on the server side.
servlet容器的基本思想就是用java去在伺服器端動態生成網頁。
So servlet container is essentially a part of a web server that interacts with the servlets.
所以servlet容器是web伺服器的一部分,與許多servlet互動。

3. What is a Servlet?

Servlet is an interface defined in javax.servlet package.
servlet是定義在javax.servlet包下的一個介面。
It declares three essential methods for the life cycle of a servlet – init(), service(), and destroy(). They are implemented by every servlet(defined in SDK or self-defined) and are invoked at specific times by the server.

* 重點 *
Each request is in its own thread, and a servlet object can serve multiple threads at the same time(thread not safe).
一個請求有一個獨立的執行緒,而一個servlet物件可以同時服務多個執行緒(因而servlet也是執行緒不安全的)
這裡寫圖片描述

4. How Servlet container and web server process a request?

1.Web server receives HTTP request
2.Web server forwards the request to servlet container
3.The servlet is dynamically retrieved and loaded into the address space of the container, if it is not in the container.
4.The container invokes the init() method of the servlet for initialization(invoked once when the servlet is loaded first time)
5.The container invokes the service() method of the servlet to process the HTTP request, i.e., read data in the request and formulate a response. The servlet remains in the container’s address space and can process other HTTP requests.
6.Web server return the dynamically generated results to the correct location

這裡寫圖片描述

5. The role of JVM

Using servlets allows the JVM to handle each request within a separate Java thread, and this is one of the key advantage of Servlet container. Each servlet is a Java class with special elements responding to HTTP requests. The main function of Servlet contain is to forward requests to correct servlet for processing, and return the dynamically generated results to the correct location after the JVM has processed them.
servlet容器的主要作用就是轉發請求給正確的servlet處理,然後再JVM處理完之後,返回動態生成的結果到正確的地址。
In most cases servlet container runs in a single JVM, but there are solutions when container need multiple JVMs.

6. 深入學習servlet

這裡寫圖片描述
The** javax.servlet **package contains many interfaces and classes that are used by the servlet or web container. These are not specific to any protocol.
被servlet和web容器使用,與具體的協議無關。

The * javax.servlet.http* package contains interfaces and classes that are responsible for http requests only.
只對http請求負責

6.1 GenericServlet

GenericServlet抽象類為Servlet介面提供了通
用實現,它與任何網路應用層協議無關。它不僅
實現了Servlet介面,還實現了ServletConfig介面
和Serializable介面,必須給出子類才能例項化。
它給出了設計servlet的一些骨架,定義得到名字、
配置、初始化引數的方法。
GenericServlet類實現了Servlet介面中的init方法,並且使得自己與一個ServletConfig物件關聯。
GenericServlet類沒有實現了Servlet介面中的serivce方法,是這個類中唯一的一個抽象方法。
GenericServlet類儘管實現了Servlet介面中的destroy方法,但是實際上什麼都沒有做。
GenericServlet類實現了Servlet介面和ServletConfig介面。它的主要身份是Servlet,此外它還運用了裝飾者模式為自己附加了ServletConfig身份。這樣它的子類就可以直接呼叫ServletConfig介面的所有方法了。

6.2 ServletConfig Interface

An object of ServletConfig is created by the web container for each servlet. This object can be used to get configuration information from web.xml file.
一個servletconfig物件是由web容器為每一個servlet建立的。(即web.xml有多少個servlet-name就有多少不同的servletconfig),這是與servletcontext的關鍵不同之處。
這個物件可以用來獲取web.xml檔案中的配置資訊。

If the configuration information is modified from the web.xml file, we don’t need to change the servlet. So it is easier to manage the web application if any specific content is modified from time to time.
如果web.xml檔案中的配置資訊被更改了,那麼我們不需要改變servlet。因此這樣更容易去管理在web應用中可能實時變化的內容。

  • Advantage of ServletConfig

The core advantage of ServletConfig is that you don’t need to edit the servlet file if information is modified from the web.xml file.
如果修改了web.xml檔案裡的內容,不需要編輯servlet檔案

  • Methods of ServletConfig interface
    1. public String getInitParameter(String name):Returns the parameter value for the specified parameter name.
    2. public Enumeration getInitParameterNames():Returns an enumeration of all the initialization parameter names.
    3. public String getServletName():Returns the name of the servlet.
    4. public ServletContext getServletContext():Returns an object of ServletContext.

example:

<web-app>  
  <servlet>  
    ......  

    <init-param>  
      <param-name>parametername</param-name>  
      <param-value>parametervalue</param-value>  
    </init-param>  
    ......  
  </servlet>  
</web-app> 
import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  

public class DemoServlet extends HttpServlet {  
public void doGet(HttpServletRequest request, HttpServletResponse response)  
    throws ServletException, IOException {  

    response.setContentType("text/html");  
    PrintWriter out = response.getWriter();  

    ServletConfig config=getServletConfig();  
    String driver=config.getInitParameter("driver");  
    out.print("Driver is: "+driver);  

    out.close();  
    }  

}  

6.4 ServletContext Interface

An object of ServletContext is created by the web container at time of deploying the project.
servletcontext物件是由web容器在部署工程時建立的。
This object can be used to get configuration information from web.xml file. There is only one ServletContext object per web application.
這個物件能用來從web.xml檔案中獲取配置資訊,一個web應用中只有一個servletcontex。
If any information is shared to many servlet, it is better to provide it from the web.xml file using the element.
如果有資訊是被許多servlet共享的,那麼最好將這個資訊放在web.xml檔案的元素裡。

  • Advantage of ServletContext
    Easy to maintain if any information is shared to all the servlet, it is better to make it available for all the servlet. We provide this information from the web.xml file, so if the information is changed, we don’t need to modify the servlet. Thus it removes maintenance problem.

  • Usage of ServletContext Interface
    There can be a lot of usage of ServletContext object. Some of them are as follows:

    1. The object of ServletContext provides an interface between the container and servlet.
    2. The ServletContext object can be used to get configuration information from the web.xml file.
    3. The ServletContext object can be used to set, get or remove attribute from the web.xml file.
    4. The ServletContext object can be used to provide inter-application communication.
  • Commonly used methods of ServletContext interface
    1.public String getInitParameter(String name):Returns the parameter value for the specified parameter name.
    2.public Enumeration getInitParameterNames():Returns the names of the context’s initialization parameters.
    3.public void setAttribute(String name,Object object):sets the given object in the application scope.
    4.public Object getAttribute(String name):Returns the attribute for the specified name.
    5.public Enumeration getInitParameterNames():Returns the names of the context’s initialization parameters as an Enumeration of String objects.
    6.public void removeAttribute(String name):Removes the attribute with the given name from the servlet context.

  • How to get the object of ServletContext interface

    1. getServletContext() method of ServletConfig interface returns the object of ServletContext.

//We can get the ServletContext object from ServletConfig object  
ServletContext application=getServletConfig().getServletContext();  
  1. getServletContext() method of GenericServlet class returns the object of ServletContext.
//Another convenient way to get the ServletContext object  
ServletContext application=getServletContext();  

example

<web-app>  

<servlet>  
<servlet-name>sonoojaiswal</servlet-name>  
<servlet-class>DemoServlet</servlet-class>  
</servlet>  

<context-param>  
<param-name>dname</param-name>  
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>  
</context-param>  

<context-param>  
<param-name>username</param-name>  
<param-value>system</param-value>  
</context-param>  

<context-param>  
<param-name>password</param-name>  
<param-value>oracle</param-value>  
</context-param>  

<servlet-mapping>  
<servlet-name>sonoojaiswal</servlet-name>  
<url-pattern>/context</url-pattern>  
</servlet-mapping>  

</web-app>    
import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  


public class DemoServlet extends HttpServlet{  
public void doGet(HttpServletRequest req,HttpServletResponse res)  
throws ServletException,IOException  
{  
res.setContentType("text/html");  
PrintWriter out=res.getWriter();  

ServletContext context=getServletContext();  
Enumeration<String> e=context.getInitParameterNames();  

String str="";  
while(e.hasMoreElements()){  
    str=e.nextElement();  
    out.print("<br> "+context.getInitParameter(str));  
}  
}}