servlet学习笔记


title: servlet学习笔记
date: 2019-11-07 21:01:05
tags:


servlet学习笔记

servlet介绍

  • 概念: servlet, server+applet的缩写,从字面上的意思去理解就是服务器和小程序,javaee api给的解释是这样子的

A servlet is a small Java program that runs within a Web server.

  • 即,servlet是一个运行在web服务器上的java小程序。javaee8 api文档

    • Interface Servlet ,servlet是一个接口,定义了java类被浏览器访问到(tomcat识别)的规则。

    • 使用servlet时,我们需要先自定义Java类,实现servlet接口,然后重写它的所有抽象方法。

    servlet_define .png

入门:

The servlet is constructed, then initialized with the init method.

Any calls from clients to the service method are handled.

The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and finalized.

  • 步骤

    1. 创建一个JavaEE项目

    2. 定义一个Java类,并且实现servlet接口
      public class ServletDemo1 implements Servlet

    3. 实现servlet接口中的所有抽象方法

      public void init(ServletConfig servletConfig) throws ServletException {
    
      }
    
      @Override
      public ServletConfig getServletConfig() {
          return null;
      }
    
      @Override
      //提供服务的方法
      public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
          System.out.println("hello servlet");
      }
    
      @Override
      public String getServletInfo() {
          return null;
      }
    
      @Override
      public void destroy() {
    
      }    
    
    1. 配置servlet
    <servlet>
        <servlet-name>demo1</servlet-name>
        <ser``vlet-class>cn.tomcat.fuzhennan.ServletDemo1</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>demo1</servlet-name>
        <url-pattern>/demo1</url-pattern>
    </servlet-mapping>  
    

servlet执行原理

  • 当用户在浏览器地址栏输入某个url路径后(我们这里用http://localhost:8080/demo1来讲解),首先会去解析web.xml文件

  • 然后在web.xml文件中找到<url-pattern>这个标签,看这个标签中是否含有/demo1这个路径

  • 如果有的话找servlet名为demo1的<servlet>,找到<servlet-class>中的内容,tomcat将全类名对应的字节码文件加载进内存,即执行Class.forName()方法

  • 创建对象 cls.newInstance();

  • 调用方法servlet中的方法

    servlet_run.png

servlet的五个抽象方法

  • init(),servlet容器在实例化servlet后会执行该方法,初始化配置信息。这个方法只会执行一次。

void init(ServletConfig config)
throws ServletException
Called by the servlet container to indicate to a servlet that the servlet is being placed into service.
The servlet container calls the init method exactly once after instantiating the servlet. The init method must complete successfully before the servlet can receive any requests.

The servlet container cannot place the servlet into service if the init method

Throws a ServletException
Does not return within a time period defined by the Web server

  • ServletConfig(),这个方法会返回一个ServletConfig对象,包括初始化的和startup的参数。

ServletConfig getServletConfig()
Returns a ServletConfig object, which contains initialization and startup parameters for this servlet. The ServletConfig object returned is the one passed to the init method.
Implementations of this interface are responsible for storing the ServletConfig object so that this method can return it. The GenericServlet class, which implements this interface, already does this.

  • service(),该方法的功能是servlet容器允许servlet响应请求,提供服务。注意,只有init()成功的执行后该方法才会执行。

Called by the servlet container to allow the servlet to respond to a request.
This method is only called after the servlet's init() method has completed successfully.

The status code of the response always should be set for a servlet that throws or sends an error.

Servlets typically run inside multithreaded servlet containers that can handle multiple requests concurrently. Developers must be aware to synchronize access to any shared resources such as files, network connections, and as well as the servlet's class and instance variables. More information on multithreaded programming in Java is available in the Java tutorial on multi-threaded programming.

  • getServletInfo(),这个方法会返回servlet的一些信息,包括作者,版本,版权等。

Returns information about the servlet, such as author, version, and copyright.
The string that this method returns should be plain text and not markup of any kind (such as HTML, XML, etc.).

  • destroy(),当servlet中的service()方法退出时,该方法就会执行,且只执行一次。当执行了该方法后,这个servlet实现的类便不会再执行service()方法。该方法可以释放任何资源。

Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. This method is only called once all threads within the servlet's service method have exited or after a timeout period has passed. After the servlet container calls this method, it will not call the service method again on this servlet.

This method gives the servlet an opportunity to clean up any resources that are being held (for example, memory, file handles, threads) and make sure that any persistent state is synchronized with the servlet's current state in memory.

servlet的生命周期

被创建

  • 执行init()方法,只执行一次
    • servlet的创建
      • 默认情况下,当第一次被访问时,servlet会被创建

      • 可以通过配置去指定servlet的创建时机

指定servlet的创建时机
1.默认情况下,第一次被访问时创建
即<load-on-startup>值为负整数,默认值为-1
2.在tomcat服务器启动时就创建
即<load-on-startup>值为>=0的整数,从0开始的整数中,越往后优先级越低,0的优先级最高

  • servlet中的init()方法只执行一次,说明一个servlet在内存中只存在一个对象,即单例模式。

    • 当用户同时访问共享资源时,对资源进行增删改查 ,可能会存在线程安全问题。

    • 解决方法:尽量不要在servlet中定义成员变量。非要定义的话不要赋值,修改。

提供服务

  • 执行service()方法,可执行多次

被销毁

  • 执行destroy()方法,只执行一次
    • 服务器正常关闭时 ,执行该方法,释放资源,servlet被销毁。

servlet3.0后的注解配置

servlet3.0之后,用户不需要手动配置web.xml文件,可以通过注解的方式去配置。

  • 实现步骤

    • 首先创建一个Javaee项目,选择servlet版本为3.0及以上,不需要勾选web.xml

    • 第二步,在src目录下创建一个Java类实现servlet接口

    • 然后重写servlet的所有抽象方法

    • 在类上通过@WebServlet()实现注解配置

  • @WebServlet()源码

public @interface WebServlet {
    String name() default "";

    String[] value() default {};

    String[] urlPatterns() default {};

    int loadOnStartup() default -1;

    WebInitParam[] initParams() default {};

    boolean asyncSupported() default false;

    String smallIcon() default "";

    String largeIcon() default "";

    String description() default "";

    String displayName() default "";
}  
  • 通过WebServlet接口我们可以看出,他底层自动帮我们初始化了这些参数,我们只需要添加自己的内容即可。

  • 我们在urlPatterns()中添加自己的路径,即可实现注解配置。如下:

@WebServlet(urlPatterns="/demo1")

  • 我们还可以对其进行简化。一般来说,WebServlet中的这些参数,value()最为重要,我们就可以把url写进value中,如果只有一个属性的话,value还可以不写,所以最终可以简写成如下:

@WebServlet("/demo1")

servlet体系结构

  • 通过看api文档,我们可以发现,还实现了三个类实现了servlet接口。
    • FacesServlet, GenericServlet, HttpServlet
    • 这里我们主要讲解后两个,通过看api文档,我们可以发现,HttpServlet是继承了GenericServlet,所以他们的关系如下:
             servlet
              |
          GenericServlet
              |
          HttpServlet  
    
    • 前面说到,我们每次新创建一个java类去实现servlet接口的时候,都必须要实现servlet接口的所有抽象方法,而实际上我们很可能只需要在service()方法里写代码,其它方法是用不到的,所以我们可以用到GenericServlet。
      • 步骤
        1. 新建一个Java类继承GenericServlet

        2. 重写service方法就好了

      • 源码分析
      • 那么为什么继承GenericServlet类就可以只需要重写service方法呢?通过源码我们可以看到,他已经自动帮我们写了其它方法,进行了空实现,在有需要的时候我们重写就行,只把service方法进行了抽象,然后只需要复写service方法就行。 部分源码如下:
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
    private static final long serialVersionUID = 1L;
    private transient ServletConfig config;

    public GenericServlet() {
    }

    public void destroy() {
    }

    public ServletConfig getServletConfig() {
        return this.config;
    }

    public String getServletInfo() {
        return "";
    }

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

    public void init() throws ServletException {
    }

    public abstract void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
}
  • HttpServlet
    • 原理

HttpServlet是对http协议进行了封装,然后重写了service方法。

  • 步骤
    1. 新建一个Java类继承HttpServlet
    2. 重写doGet()/doPost()方法。(注意,在浏览器地址栏输入url是get请求,post请求得用表单的方式进行)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260