Servlet、Servlet容器、Servlet容器与Web Server关系、Servlet生命周期

一、Static WebPage

早期,客户端只能从服务端请求静态网页
在这里插入图片描述

二、Dynamic WebPage、Web Server与Servlet Container关系

Dynamic web content is the content that changes with every user request. This type of web application let the users personalize the content according to their preferences.
动态网页会随着用户请求不同而显示不同内容。通过用户偏好,个性化内容。

To build such a powerful web app, you need Java technologies, like servlet and JSP. Web Server is mostly designed to serve static HTML content. For this type of app, web server needed a servlet plugin that can communicate with or build dynamic pages.
为了增强web应用,需要servlet+jsp。一般,Web Server为静态HTML内容服务。为了动态显示,需要使用servlet插件,来构建动态页面。

Servlet plugin is also called as servlet container or web container.
在这里插入图片描述
Servlets were Java’s first server-side web technology. A Servlet is an ordinary Java class that implements a special Servlet interface. This class is then deployed in a Servlet container. The servlet doesn’t talk to the client directly. The Web server functions as the intermediary that does it for the servlet. In a chain of processes, the client sends a request to the Web server, which hands it to the container, which hands it to the servlet. The Servlet processes the request and generates a response. The response starts from the servlet and goes to the container and then to the Web server and back to the client. Of course there are several other steps that happen too but this is just the introduction so this much would suffice I believe.
Servlet是Java的首个服务器端Web技术。Servlet是实现Servlet接口的普通Java类。然后,将此类部署在Servlet容器中。Servlet不会直接与Client对话。 Web Server充当Client与servlet交流的中介。Servlet Container工作过程:Client将请求发送到Web Server,然后将请求传递到Servlet Container,Servlet Container传递给servlet。 Servlet处理完请求并生成响应。 响应从Servlet开始,到达Servlet Container,然后到达Web Server,再返回到Client。 这只是大致步骤,比如还有filter。

Today most servlet containers come with built-in web servers, so you do not often make the distinction between a Java web server and a Java servlet container. Examples of Java web servers with servlet containers are Apache Tomcat, GlassFish, Jetty, JBoss etc.
如今,Web Server一般包含Servlet Container,因此您不必经常在Web Server和Servlet Container进行区分。带有Servlet Container的Java Web Server有Apache Tomcat,GlassFish,Jetty,JBoss等。
在这里插入图片描述

三、Servlet Container

在这里插入图片描述
A web container (also known as a servlet container; and compare “webcontainer”) is the component of a web server that interacts with Java servlets. A web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access-rights.
Web Container(也叫Servlet Container)是Web Server组件,用于与Java Servlet交互。(因为自定义Servlet并没有main,不能独立运行,它必须部署到Servlet Container中,由它实例化和调用Servlet的方法)。Servlet Container负责管理Servlet的生命周期,将URL映射到特定的Servlet并确保URL请求者具有正确的访问权限。

A web container handles requests to servlets, JavaServer Pages (JSP) files, and other types of files that include server-side code. The Web container creates servlet instances, loads and unloads servlets, creates and manages request and response objects, and performs other servlet-management tasks.
Servlet Container能够处理对servlet,JavaServer Pages(JSP)以及其他包含服务器端代码的文件类型的请求。Servlet Container创建servlet实例,加载和卸载servlet,创建和管理请求和响应对象,并执行其他servlet管理任务。

A web container implements the web component contract of the Java EE architecture. This architecture specifies a runtime environment for additional web components, including security, concurrency, lifecycle management, transaction, deployment, and other services.
Servlet Container实现Java EE体系结构的Web组件协定。此体系结构为其他Web组件指定了运行时环境,包括安全性,并发性,生命周期管理,事务,部署和其他服务。

四、Servlet Life Cycle

在这里插入图片描述

①init()

The init method is called only once. It is called only when the servlet is created, and not called for any user requests afterwards.
init()仅被调用一次。时机:创建servlet时,此后不为任何用户请求调用。

The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.
何时创建servlet:通常,在用户首次调用与该servlet相对应的URL时创建servlet,但是您也可以指定在首次启动服务器时加载servlet。

When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.
当用户调用servlet时,会为此servlet创建单例,每个用户请求都会产生一个新线程,该线程将适当地移交给doGet或doPost

(类比)单例,多线程实现Runnable接口:https://blog.csdn.net/jiangshangchunjiezi/article/details/88118063

init()方法做什么:init()方法仅加载一些将在servlet的整个生命周期内使用的数据。

public void init() throws ServletException {
   // Initialization code...
}
②service(req,resp)

The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.
service()方法执行实际任务的主要方法。Servlet Container调用service()方法来处理来自客户端(浏览器)的请求,并将格式化后的响应写回到客户端。

Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
每次服务器收到对Servlet的请求时,服务器都会产生一个新线程并调用服务。service()方法检查HTTP请求类型(GET,POST,PUT,DELETE等),并在适当时调用doGet,doPost,doPut,doDelete等方法。

 protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getMethod();
        long lastModified;
        if (method.equals("GET")) {
                    this.doGet(req, resp);
        } else if (method.equals("HEAD")) {
           
            this.doHead(req, resp);
        } //略其他....
        else {
            String errMsg = lStrings.getString("http.method_not_implemented");
            Object[] errArgs = new Object[]{method};
            errMsg = MessageFormat.format(errMsg, errArgs);
            resp.sendError(501, errMsg);
        }

    }
③destroy()

The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.
在Servlet的生命周期结束时,只会调用一次destroy()方法。
destroy()作什么:在servlet中可能开启某些资源,此处用于关闭数据库连接,暂停后台线程,将Cookie列表或命中计数写入磁盘,以及执行其他此类清理活动。

根据Servlet生命周期,再次理解Servlet Container工作过程
  • A client makes an HTTP request to the Web server via a Web browser.
  • The Web server delegates the request to the servlet container. The container may be running as the same process as the network services or a different process on the same host.
  • Depending upon the configuration of the servlet, the container invokes the appropriate servlet class with the response/request object. ①
  • The request object provides information about the remote user, HTTP POST parameters, and other details. Once these details are known, the servlet processes the data according to the program logic and then sends back to the client via a response object.
  • The servlet container returns the control back to the Web server after request processing is finished.
    对①解释:appropriate servlet
web.xml:
    <!--注册servlet-->
    <servlet>
        <servlet-name>HelloWorld</servlet-name>
        <servlet-class>HelloWorld</servlet-class>
    </servlet>
    
   <!--指定特定请求所用的servlet-->
    <servlet-mapping>
        <servlet-name>HelloWorld</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>

<body>
<form action="login" method="post" >
  username:<input type="text" name="username" ><br>
  password:<input type="password" name="pwd" ><br>
    <input type="submit" value="sign in"/>
</form>
</body>
</html>

参考:
http://www.beginwithjava.com/servlet-jsp/web-application-overview/servlet-container.html
https://en.wikipedia.org/wiki/Web_container
https://zhuanlan.zhihu.com/p/40249834
http://www.edu4java.com/en/servlet/servlet1.html
https://www.youtube.com/watch?v=RJYxr7ThD00

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值