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));  
}  
}}  

猜你喜欢

转载自blog.csdn.net/normol/article/details/79872824