4 JavaWeb technology into the world: Servlet working principle Detailed

This series of articles will arrange to me on GitHub's "Java Interview Guide" warehouse, more exciting content please go to my warehouse View

https://github.com/h2pl/Java-Tutorial

Like it under the trouble spots Star Kazakhstan

Article first appeared in my personal blog:

www.how2playlife.com

This article is a micro-channel public number [of] Java technology rivers and lakes "into JavaWeb technology world" in which a Part of this article from the network, to the subject of this article speaks clear and thorough, and I think a lot of good integration of technology blog content, which cited a number of good blog posts, if infringement, please contact the author.

This blog series will show you how to from entry to advanced, from servlet to the frame, and then from ssm SpringBoot, step by step JavaWeb learn the basics and get started actual combat, and then to understand the technical components of the project JavaWeb often used, including log component, Maven, Junit, and much more, in order to make you a more complete understanding of the entire Java Web technology system, to form their own intellectual framework.

In order to summarize and test your learning outcomes, this series will provide every knowledge point corresponding interview questions and suggested answers.

If you have any suggestions for this series of articles, or have any questions, you can also concerned about the number of public rivers and lakes [] Java technology to contact the author, you are welcome to participate in the creation and revision of this blog series.

What is Servlet

Servlet role is to provide a unified specification for the Java programming web applications to facilitate unified programmer to write programs using this specification, the application can use the specifications provided by the container to achieve their own characteristics. For example, code and code jetty tomcat is not the same, but as a programmer you only need to know the values from the servlet specification can request, you can operate the session, and so on. Do not care about the difference between the application server to achieve the underlying affect your development.

HTTP protocol is only a standard, substantially Shape define the service request and response. Java servlet class will HTTP in those low-level packaged in a Java class structure , convenient methods of these classes included making it easier to handle in the Java language environment.

As specific servlet container you are using a profile defined, when the user issues a request through the URL, the Java servlet classes will convert it into a HttpServletRequest, sent to the target URL is directed. When the server completes its work, Java Runtime Environment (Java Runtime Environment) will result in a packaged HttpServletResponse, and then returned to the original HTTP response sent to the requesting client. When interacting with a Web application, typically a plurality of multiple requests and get responses. All of this is in the context of a conversation, Java language in a package of HttpSession object. In dealing with the response, you can access the object and to add an event when you create a response. It provides some context across requests.

Container (such as Tomcat) servlet will manage the runtime environment. You can configure the container, customized J2EE server works so that the servlet exposed to the outside world. As we will see, through the container in a variety of profiles, you (entered by the user in a browser) in the URL between the server-side components and build a bridge, you'll need these components will handle the conversion URL request. When you run the application, the container loads and initializes the servlet , manage their life cycle .

Servlet architecture

4 JavaWeb technology into the world: Servlet working principle Detailed

Servlet top-class correlation graph

Servlet

Servlet framework consists of two Java packages consisting of: javax.servlet and javax.servlet.http. Servlet defines all classes must implement javax.servlet package or extended generic classes and interfaces. HttpServlet class defines protocol for communication using Http javax.servlet.http package. The core of the Servlet framework is javax.servlet.Servlet interfaces, all of the Servlet must implement this interface.

4 JavaWeb technology into the world: Servlet working principle Detailed

Servlet interface

5 defines a Servlet interface methods:

1\. init(ServletConfig)方法:负责初始化Servlet对象,在Servlet的生命周期中,该方法执行一次;该方法执行在单线程的环境下,因此开发者不用考虑线程安全的问题;
2\. service(ServletRequest req,ServletResponse res)方法:负责响应客户的请求;为了提高效率,Servlet规范要求一个Servlet实例必须能够同时服务于多个客户端请求,即service()方法运行在多线程的环境下,Servlet开发者必须保证该方法的线程安全性;
3\. destroy()方法:当Servlet对象退出生命周期时,负责释放占用的资源;
4\. getServletInfo:就是字面意思,返回Servlet的描述;
5\. getServletConfig:这个方法返回由Servlet容器传给init方法的ServletConfig。

ServletRequest & ServletResponse

For every HTTP request, creates a servlet container encapsulates HTTP request transmitted to the service servlet method ServletRequest instance, the ServletResponse response indicates a Servlet, which hides the complexity of the response to the browser. You can get some requests by the method of ServletRequest relevant parameters, and you can set some ServletResponse return parameter information, and set the return content.

ServletConfig

ServletConfig package may pass through a Servlet web.xml @WebServlet or configuration information, each piece of information transmitted in this way are called initialization information, initialization information is one KV pairs. In order to obtain an initial value of a parameter from an internal Servlet, init method call a method or getinitParameterNames getinitParameter ServletConfig the method to obtain, in addition, you may also be obtained by ServletContext object getServletContext.

ServletContext

ServletContext represent the Servlet applications. Each Web application has only one context. In a distributed environment, deploy an application to multiple containers, and each Java virtual machine has a ServletContext object. All information resource access after the ServletContext object, you can share by application, to promote the dynamic registration Web objects, shared by an internal Map of objects stored in ServiceContext be achieved. ServletContext object stored in the referred properties. The method of operation of properties:

GenericServlet

Front Servlet application written in written by implementing Servlet Servlet interface, but every time we must all methods are provided in the Servlet implementation also need to save ServletConfig object to a class-level variable, GenericServlet is an abstract class is to we omit some template code that implements the Servlet and ServletConfig, completed at several jobs:

The init method ServletConfig assigned to a variable class-level, so that can be obtained by getServletConfig.

public void init(ServletConfig config) throws ServletException {
        this.config = config;
        this.init();
}

In order to avoid the rear cover while init method must be called super.init (servletConfig) in a subclass, the GenericServlet init is also provided a method without parameters, the assignment is completed when ServletConfig init method will be called first parameters. This cover can not write the init method parameter initialization code, while still preserved example ServletConfig

It provides default implementations for all methods Servlet interface.

To provide a method of packaging methods ServletConfig.

HTTPServlet

In the preparation of Servlet application, to be used in the majority of HTTP, which means you can take advantage of the characteristics provided by HTTP, javax.servlet.http contains classes and interfaces written in Servlet applications, many of which are covered javax.servlet type, most of the time we ourselves are inherited when writing applications HttpServlet.

Servlet working principle

When the Web server receives an HTTP request, it first determines whether the requested content - if the data is a static page, the Web server will handle, and then generates the response information; if the dynamic data involved, the Web server forwards the request to the Servlet container. At this time, the vessel will find Servlet Servlet example of the processing of the request corresponding to the processing results are sent back to the Web server, the Web server then returned to the client.

, Servlet container creates a Servlet Servlet examples for the same at the first http request is received, and then start a thread. The second time received http request, Servlet Servlet containers do not need to create the same instance, but start a second thread to service client requests. So multiple threads can not only improve the efficiency of Web applications, the system can also reduce the burden on Web servers.

4 JavaWeb technology into the world: Servlet working principle Detailed

Web server workflow

Then we describe the Tomcat Servlet and how it works, first of all look at the timing diagram below:

4 JavaWeb technology into the world: Servlet working principle Detailed

Servlet working principle of timing diagram

  1. Issuing a request to the Web Client Http Servlet container (the Tomcat);

  2. Web Client Servlet container receiving a request;

  3. Servlet container creates an HttpRequest object, the encapsulation information to the Web Client requested object;

  4. Servlet container creates an HttpResponse;

  5. HttpServlet object Servlet container calls the service method, the object HttpRequest HttpResponse object HttpServlet object is passed as a parameter;

  6. HttpServlet call about the method HttpRequest object, Http request to obtain information;

  7. For a method call HttpResponse HttpServlet object, generating response data;

  8. The response result Servlet Container HttpServlet passed to Web Client;

Servlet life cycle

The method defined in Servlet interface 5, where the three methods represent Servlet life cycle:

1\. init(ServletConfig)方法:负责初始化Servlet对象,在Servlet的生命周期中,该方法执行一次;该方法执行在单线程的环境下,因此开发者不用考虑线程安全的问题;
2\. service(ServletRequest req,ServletResponse res)方法:负责响应客户的请求;为了提高效率,Servlet规范要求一个Servlet实例必须能够同时服务于多个客户端请求,即service()方法运行在多线程的环境下,Servlet开发者必须保证该方法的线程安全性;
3\. destroy()方法:当Servlet对象退出生命周期时,负责释放占用的资源;

Programming Notes Description:

  1. 当Server Thread线程执行Servlet实例的init()方法时,所有的Client Service Thread线程都不能执行该实例的service()方法,更没有线程能够执行该实例的destroy()方法,因此Servlet的init()方法是工作在单线程的环境下,开发者不必考虑任何线程安全的问题。
  2. 当服务器接收到来自客户端的多个请求时,服务器会在单独的Client Service Thread线程中执行Servlet实例的service()方法服务于每个客户端。此时会有多个线程同时执行同一个Servlet实例的service()方法,因此必须考虑线程安全的问题。
  3. 虽然service()方法运行在多线程的环境下,并不一定要同步该方法。而是要看这个方法在执行过程中访问的资源类型及对资源的访问方式。分析如下:
1\. 如果service()方法没有访问Servlet的成员变量也没有访问全局的资源比如静态变量、文件、数据库连接等,而是只使用了当前线程自己的资源,比如非指向全局资源的临时变量、request和response对象等。该方法本身就是线程安全的,不必进行任何的同步控制。

2\. 如果service()方法访问了Servlet的成员变量,但是对该变量的操作是只读操作,该方法本身就是线程安全的,不必进行任何的同步控制。

3\. 如果service()方法访问了Servlet的成员变量,并且对该变量的操作既有读又有写,通常需要加上同步控制语句。

4\. 如果service()方法访问了全局的静态变量,如果同一时刻系统中也可能有其它线程访问该静态变量,如果既有读也有写的操作,通常需要加上同步控制语句。

5\. 如果service()方法访问了全局的资源,比如文件、数据库连接等,通常需要加上同步控制语句。

在创建一个 Java servlet 时,一般需要子类 HttpServlet。该类中的方法允许您访问请求和响应包装器(wrapper),您可以用这个包装器来处理请求和创建响应。Servlet的生命周期,简单的概括这就分为四步:

Servlet类加载--->实例化--->服务--->销毁;

4 JavaWeb technology into the world: Servlet working principle Detailed

Servlet生命周期

创建Servlet对象的时机:

  1. 默认情况下,在Servlet容器启动后:客户首次向Servlet发出请求,Servlet容器会判断内存中是否存在指定的Servlet对象,如果没有则创建它,然后根据客户的请求创建HttpRequest、HttpResponse对象,从而调用Servlet对象的service方法;
  2. Servlet容器启动时:当web.xml文件中如果<servlet>元素中指定了<load-on-startup>子元素时,Servlet容器在启动web服务器时,将按照顺序创建并初始化Servlet对象;
  3. Servlet的类文件被更新后,重新创建Servlet。Servlet容器在启动时自动创建Servlet,这是由在web.xml文件中为Servlet设置的<load-on-startup>属性决定的。从中我们也能看到同一个类型的Servlet对象在Servlet容器中以单例的形式存在;

注意:在web.xml文件中,某些Servlet只有<serlvet>元素,没有<servlet-mapping>元素,这样我们无法通过url的方式访问这些Servlet,这种Servlet通常会在<servlet>元素中配置一个<load-on-startup>子元素,让容器在启动的时候自动加载这些Servlet并调用init(ServletConfig config)方法来初始化该Servlet。其中方法参数config中包含了Servlet的配置信息,比如初始化参数,该对象由服务器创建。

销毁Servlet对象的时机:

Servlet容器停止或者重新启动:Servlet容器调用Servlet对象的destroy方法来释放资源。以上所讲的就是Servlet对象的生命周期。那么Servlet容器如何知道创建哪一个Servlet对象?Servlet对象如何配置?实际上这些信息是通过读取web.xml配置文件来实现的。

<servlet>
    <!-- Servlet对象的名称 -->
    <servlet-name>action<servlet-name>
    <!-- 创建Servlet对象所要调用的类 -->
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
        <!-- 参数名称 -->
        <param-name>config</param-name>
        <!-- 参数值 -->
        <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
        <param-name>detail</param-name>
        <param-value>2</param-value>
    </init-param>
    <init-param>
        <param-name>debug</param-name>
        <param-value>2</param-value>
    </init-param>
    <!-- Servlet容器启动时加载Servlet对象的顺序 -->
    <load-on-startup>2</load-on-startup>
</servlet>
<!-- 要与servlet中的servlet-name配置节内容对应 -->
<servlet-mapping>
    <servlet-name>action</servlet-name>
    <!-- 客户访问的Servlet的相对URL路径 -->
    <url-pattern>*.do</url-pattern>
</servlet-mapping>

当Servlet容器启动的时候读取<servlet>配置节信息,根据<servlet-class>配置节信息创建Servlet对象,同时根据<init-param>配置节信息创建HttpServletConfig对象,然后执行Servlet对象的init方法,并且根据<load-on-startup>配置节信息来决定创建Servlet对象的顺序,如果此配置节信息为负数或者没有配置,那么在Servlet容器启动时,将不加载此Servlet对象。当客户访问Servlet容器时,Servlet容器根据客户访问的URL地址,通过<servlet-mapping>配置节中的<url-pattern>配置节信息找到指定的Servlet对象,并调用此Servlet对象的service方法。

在整个Servlet的生命周期过程中,创建Servlet实例、调用实例的init()和destroy()方法都只进行一次,当初始化完成后,Servlet容器会将该实例保存在内存中,通过调用它的service()方法,为接收到的请求服务。下面给出Servlet整个生命周期过程的UML序列图,如图所示:

4 JavaWeb technology into the world: Servlet working principle Detailed

Servlet生命周期

如果需要让Servlet容器在启动时即加载Servlet,可以在web.xml文件中配置<load-on-startup>元素。

Servlet中的Listener

Listener 使用的非常广泛,它是基于观察者模式设计的,Listener 的设计对开发 Servlet 应用程序提供了一种快捷的手段,能够方便的从另一个纵向维度控制程序和数据。目前 Servlet 中提供了 5 种两类事件的观察者接口,它们分别是:4 个 EventListeners 类型的,ServletContextAttributeListener、ServletRequestAttributeListener、ServletRequestListener、HttpSessionAttributeListener 和 2 个 LifecycleListeners 类型的,ServletContextListener、HttpSessionListener。如下图所示:

4 JavaWeb technology into the world: Servlet working principle Detailed

Servlet中的Listener

它们基本上涵盖了整个 Servlet 生命周期中,你感兴趣的每种事件。这些 Listener 的实现类可以配置在 web.xml 中的 <listener> 标签中。当然也可以在应用程序中动态添加 Listener,需要注意的是 ServletContextListener 在容器启动之后就不能再添加新的,因为它所监听的事件已经不会再出现。掌握这些 Listener 的使用,能够让我们的程序设计的更加灵活。

Cookie与Session

Servlet 能够给我们提供两部分数据,一个是在 Servlet 初始化时调用 init 方法时设置的 ServletConfig,这个类基本上含有了 Servlet 本身和 Servlet 所运行的 Servlet 容器中的基本信息。还有一部分数据是由 ServletRequest 类提供,从提供的方法中发现主要是描述这次请求的 HTTP 协议的信息。关于这一块还有一个让很多人迷惑的 Session 与 Cookie。

Session 与 Cookie 的作用都是为了保持访问用户与后端服务器的交互状态。它们有各自的优点也有各自的缺陷。然而具有讽刺意味的是它们优点和它们的使用场景又是矛盾的,例如使用 Cookie 来传递信息时,随着 Cookie 个数的增多和访问量的增加,它占用的网络带宽也也会越来越大。所以大访问量的时候希望用 Session,但是 Session 的致命弱点是不容易在多台服务器之间共享,所以这也限制了 Session 的使用。

不管 Session 和 Cookie 有什么不足,我们还是要用它们。下面详细讲一下,Session 如何基于 Cookie 来工作。实际上有三种方式能可以让 Session 正常工作:

  • 基于 URL Path Parameter,默认就支持
  • 基于 Cookie,如果你没有修改 Context 容器个 cookies 标识的话,默认也是支持的
  • 基于 SSL,默认不支持,只有 connector.getAttribute("SSLEnabled") 为 TRUE 时才支持

第一种情况下,当浏览器不支持 Cookie 功能时,浏览器会将用户的 SessionCookieName 重写到用户请求的 URL 参数中,它的传递格式如:

 /path/Servlet?name=value&name2=value2&JSESSIONID=value3

接着 Request 根据这个 JSESSIONID 参数拿到 Session ID 并设置到 request.setRequestedSessionId 中。

请注意如果客户端也支持 Cookie 的话,Tomcat 仍然会解析 Cookie 中的 Session ID,并会覆盖 URL 中的 Session ID。

如果是第三种情况的话将会根据 javax.servlet.request.ssl_session 属性值设置 Session ID。

有了 Session ID 服务器端就可以创建 HttpSession 对象了,第一次触发是通过 request. getSession() 方法,如果当前的 Session ID 还没有对应的 HttpSession 对象那么就创建一个新的,并将这个对象加到 org.apache.catalina. Manager 的 sessions 容器中保存,Manager 类将管理所有 Session 的生命周期,Session 过期将被回收,服务器关闭,Session 将被序列化到磁盘等。只要这个 HttpSession 对象存在,用户就可以根据 Session ID 来获取到这个对象,也就达到了状态的保持。

4 JavaWeb technology into the world: Servlet working principle Detailed

Session相关类图

上从图中可以看出从 request.getSession 中获取的 HttpSession 对象实际上是 StandardSession 对象的门面对象,这与前面的 Request 和 Servlet 是一样的原理。下图是 Session 工作的时序图:

4 JavaWeb technology into the world: Servlet working principle Detailed

Session工作的时序图

还有一点与 Session 关联的 Cookie 与其它 Cookie 没有什么不同,这个配置的配置可以通过 web.xml 中的 session-config 配置项来指定。

参考文章

<https://segmentfault.com/a/1190000009707894>;

<https://www.cnblogs.com/hysum/p/7100874.html>;

<http://c.biancheng.net/view/939.html>;

<https://www.runoob.com/>;

https://blog.csdn.net/android_hl/article/details/53228348

Guess you like

Origin blog.51cto.com/14006572/2444339