当使用spring-Boot时,嵌入式Servlet容器通过扫描注解的方式注册Servlet、Filter和Servlet规范的所有监听器(如HttpSessionListener监听器)。
Spring boot 的主 Servlet 为 DispatcherServlet,其默认的url-pattern为“/”。也许我们在应用中还需要定义更多的Servlet,该如何使用SpringBoot来完成呢?

在spring boot中添加自己的Servlet有两种方法,代码注册Servlet和注解自动注册(Filter和Listener也是如此)。
一、代码注册通过ServletRegistrationBean、 FilterRegistrationBean 和 ServletListenerRegistrationBean 获得控制。
也可以通过实现 ServletContextInitializer 接口直接注册。

二、在 SpringBootApplication 上使用@ServletComponentScan
注解后,Servlet、Filter、Listener 可以直接通过 @WebServlet、@WebFilter、@WebListener
注解自动注册,无需其他代码。

1.通过代码注册Servlet示例代码

1).SpringBootSimpleApplication.Java类:

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

import com.example.servlet.MyServlet;

@SpringBootApplication
public class SpringBootSimpleApplication {
    /**
     * 使用代码注册Servlet(不需要@ServletComponentScan注解)
     */
    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        return new ServletRegistrationBean(new MyServlet(), "/st/*");// ServletName默认值为首字母小写,即myServlet
    }
    public static void main(String[] args) {
        SpringApplication.run(SpringBootSimpleApplication.class, args);
    }
}

2).MyServlet.java类:

package com.example.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(">>>>>>>>>>doGet()<<<<<<<<<<<");
        doPost(req, resp);
    }

@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(">>>>>>>>>>doPost()<<<<<<<<<<<");
        resp.setContentType("text/html");  
        resp.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();  
        out.println("<html>");  
        out.println("<head>");  
        out.println("<title>Hello World</title>");  
        out.println("</head>");  
        out.println("<body>");  
        out.println("<h1>大家好,我的名字叫Servlet</h1>");  
        out.println("</body>");  
        out.println("</html>");
    }
}

2.使用注解注册Servlet示例代码

1).SpringBootSimpleApplication.java类:

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

import com.example.servlet.MyServlet;

@SpringBootApplication
@ServletComponentScan
public class SpringBootSimpleApplication {
    /**
     * 使用代码注册Servlet(不需要@ServletComponentScan注解)
     */
    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        return new ServletRegistrationBean(new MyServlet(), "/st/*");// ServletName默认值为首字母小写,即myServlet
    }
    public static void main(String[] args) {
        SpringApplication.run(SpringBootSimpleApplication.class, args);
    }
}

2).MyServlet2.java类:

package com.example.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 不指定name的情况下,name默认值为类全路径,即com.example.servlet.MyServlet2
@WebServlet(urlPatterns="/st/myservlet2", description="Servlet的说明")
public class Myservlet2 extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(">>>>>>>>>>doGet2()<<<<<<<<<<<");
        doPost(req, resp);
    }

@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(">>>>>>>>>>doPost2()<<<<<<<<<<<");
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();  
        out.println("<html>");  
        out.println("<head>");  
        out.println("<title>Hello World</title>");  
        out.println("</head>");  
        out.println("<body>");  
        out.println("<h1>大家好,我的名字叫Servlet2</h1>");  
        out.println("</body>");  
        out.println("</html>");
    }
}

使用 @WebServlet 注解,其中可以设置一些属性。

3.访问结果

4.DispatcherServlet默认拦截

DispatcherServlet 默认拦截“/”,MyServlet 拦截“/st/*”,MyServlet2
拦截“/st/myservlet”,那么在我们访问 http://localhost:8080/st/myservlet2
的时候系统会怎么处理呢?如果访问
http://localhost:8080/st/abc的时候又是什么结果呢?其结果是“匹配的优先级是从精确到模糊,复合条件的Servlet并不会都执行”。
既然系统DispatcherServlet 默认拦截“/”,那么我们是否能做修改呢,答案是肯定的,我们在SpringBootSampleApplication中添加代码:

/**
     * 修改DispatcherServlet默认配置
     */
    @Bean
    public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
        ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet);
        registration.getUrlMappings().clear();
        registration.addUrlMappings("*.do");
        registration.addUrlMappings("*.json");
        return registration;
    }

可以通过注入DispatcherServlet 然后用ServletRegistrationBean包裹一层 动态的加上一些初始参数。

Spring Boot的Servlet简单使用的更多相关文章

  1. spring boot整合servlet、filter、Listener等组件方式

    创建一个maven项目,然后此项目继承一个父项目:org.springframework.boot 1.创建一个maven项目: 2.点击next后配置父项目及版本号 3.点击finish后就可查看p ...

  2. Spring Boot 集成servlet,发布为可直接运行的war包,方便后续打包为docker镜像。

    背景:Spring Boot 集成servlet,发布为可直接运行的war包,方便后续打包为docker镜像. 原文地址 https://github.com/weibaohui/springboot ...

  3. Spring Boot 注册 Servlet 的三种方法,真是太有用了!

    本文栈长教你如何在 Spring Boot 注册 Servlet.Filter.Listener. 你所需具备的基础 什么是 Spring Boot? Spring Boot 核心配置文件详解 Spr ...

  4. Spring Boot整合Servlet,Filter,Listener,访问静态资源

    目录 Spring Boot整合Servlet(两种方式) 第一种方式(通过注解扫描方式完成Servlet组件的注册): 第二种方式(通过方法完成Servlet组件的注册) Springboot整合F ...

  5. Spring Boot 系列 - WebSocket 简单使用

    在实现消息推送的项目中往往需要WebSocket,以下简单讲解在Spring boot 中使用 WebSocket. 1.pom.xml 中引入 spring-boot-starter-websock ...

  6. spring boot(18)-servlet、filter、listener

    servlet.filter.listener的用法就不讲了,只讲如何在spring boot中配置它们.有两种方式,一种是从servlet3开始提供的注解方式,另一种是spring的注入方式 ser ...

  7. Spring Boot (19) servlet、filter、listener

    servlet.filter.listener,在spring boot中配置方式有两种:一种是以servlet3开始提供的注解方式,另一种是spring的注入方式. servlet注解方式 serv ...

  8. spring boot中servlet启动原理

    启动过程及原理 1 spring boot 应用启动运行run方法 StopWatch stopWatch = new StopWatch(); stopWatch.start(); Configur ...

  9. spring boot配置Servlet容器

    Spring boot 默认使用Tomcat作为嵌入式Servlet容器,只需要引入spring-boot-start-web依赖,默认采用的Tomcat作为容器 01  定制和修改Servlet容器 ...

随机推荐

  1. java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing,

    缺少一个java包,然后我在这个网址找到了http://central.maven.org/maven2/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1. ...

  2. hadoop 学习之异常篇

    本文旨在给予自己在学习hadoop过程中遇到的问题的一个记录和解决方法. 一. copyFromLocal: java.io.IOException: File /user/hadoop/slaves ...

  3. Redis java client ==> Jedis

    https://github.com/xetorthio/jedis Jedis is a blazingly small and sane Redis java client. Jedis was ...

  4. /usr/include/boost/python/detail/wrap_python.hpp:50:23: fatal error: pyconfig.h: No such file or directory

    https://stackoverflow.com/questions/39111930/usr-include-boost-python-detail-wrap-python-hpp5023-fat ...

  5. day01(静态、代码块、类变量和实类变量辨析 )

    静态: 关键字:static          概述: 使用static关键字修饰的成员方法.成员变量称为静态成员方法.静态成员变量.    优缺点:   优点:使用时不用创建对象,节约了空间.使得代 ...

  6. (最小生成树) 畅通工程再续 -- HDU --1875

    链接: http://acm.hdu.edu.cn/showproblem.php?pid=1875 http://acm.hust.edu.cn/vjudge/contest/view.action ...

  7. Delphi事件的广播 转

    http://blog.sina.com.cn/s/blog_44fa172f0102wgs2.html 原文地址:Delphi事件的广播 转作者:MondaySoftware 明天就是五一节了,辛苦 ...

  8. Python学习-33.Python中glob模块的一些参数

    glob模块中有一个叫glob的方法可以获取某个目录下的文件. import glob temp=glob.glob("E:\\Temp\\*.txt") print(temp) ...

  9. Thread in depth 2:Asynchronization and Task

    When we want to do a work asynchronously, creating a new thread is a good way. .NET provides two oth ...

  10. linux系统编程之进程(七):system()函数使用

    一,system()理解 功能:system()函数调用"/bin/sh -c command"执行特定的命令,阻塞当前进程直到command命令执行完毕 原型: int syst ...