当使用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. cmake-include_directories

    include_directories: Add include directories to the build. include_directories([AFTER|BEFORE] [SYSTE ...

  2. VS2010程序打包操作--超详细

    1.  在vs2010 选择“新建项目”----“其他项目类型”----“Visual Studio Installerà“安装项目”: 命名为:Setup1 . 这是在VS2010中将有三个文件夹, ...

  3. hdu 2063 匈牙利算法

    http://acm.hdu.edu.cn/showproblem.php?pid=2063 男女配对最大数 匈牙利算法模板 #include <cstdio> #include < ...

  4. Socket常用语法与socketserver实例

    1>Socket相关: 1>Socket   Families(地址簇): socket.AF_UNIX   本机进程间通信 socket.AF_INET IPV4 socket.AF_I ...

  5. C++ 补遗

    C++通过引用传递数组 数组形参可以声明为数组的引用.如果形参是数组的引用,编译器不会将数组实参转化为指针,而是传递数组的引用本身. 在这种情况下,数组大小成为形参和实参类型的一部分(实参长度与形参长 ...

  6. 微信公众平台如何与Web App结合?

    Web App简而言之就是为移动平台而优化的网页,它可以表现得和原生应用一样,并且克服了原生应用一些固有的缺点.一般而言Web App最大的入口是浏览器,但现在微信公众平台作为新兴的平台,结合其内置浏 ...

  7. GitHub Android 开源项目汇总 (转)

    转自:http://blog.csdn.net/ithomer/article/details/8882236 GitHub 上的开源项目不胜枚举,越来越多的开源项目正在迁移到GitHub平台上.基于 ...

  8. asp.net使用SpeechSynthesizer类生成语音文件部署到iis遇到的几个坑

    首先需要引入命名空间System.Speech.Synthesis,代码如下: using (var speechSyn = new SpeechSynthesizer()) { speechSyn. ...

  9. Hibernate一级缓存测试分析

    Hibernate 一级缓存测试分析 Hibernate的一级缓存就是指Session缓存,此Session非http的session会话技术,可以理解为JDBC的Connection,连接会话,Se ...

  10. 利用MVC5+EF6搭建博客系统

    https://www.cnblogs.com/wyt007/p/7880137.html