Web开发使用 Controller 基本上可以完成大部分需求,但是我们还可能会用到 Servlet、Filter、Listener、Interceptor 等等。

当使用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 注解自动注册,无需其他代码。

通过代码注册Servlet示例代码:

SpringBootSampleApplication.Java

package org.springboot.sample;

import org.springboot.sample.servlet.MyServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.DispatcherServlet; @SpringBootApplication
public class SpringBootSampleApplication { /**
* 使用代码注册Servlet(不需要@ServletComponentScan注解)
*
*/
@Bean
public ServletRegistrationBean servletRegistrationBean() {
return new ServletRegistrationBean(new MyServlet(), "/xs/*");// ServletName默认值为首字母小写,即myServlet
} public static void main(String[] args) {
SpringApplication.run(SpringBootSampleApplication.class, args);
}
}

MyServlet.java

package org.springboot.sample.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; /**
* Servlet
*
*/
//@WebServlet(urlPatterns="/xs/*", description="Servlet的说明")
public class MyServlet extends HttpServlet{ private static final long serialVersionUID = -8685285401859800066L; @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");
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>");
} }

使用注解注册Servlet示例代码

SpringBootSampleApplication.java

package org.springboot.sample;

import org.springboot.sample.servlet.MyServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.DispatcherServlet; @SpringBootApplication
@ServletComponentScan
public class SpringBootSampleApplication { public static void main(String[] args) {
SpringApplication.run(SpringBootSampleApplication.class, args);
}
}

MyServlet2.java

package org.springboot.sample.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; /**
* Servlet
*
*/
@WebServlet(urlPatterns="/xs/myservlet", description="Servlet的说明") // 不指定name的情况下,name默认值为类全路径,即org.springboot.sample.servlet.MyServlet2
public class MyServlet2 extends HttpServlet{ private static final long serialVersionUID = -8685285401859800066L; @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");
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 注解,其中可以设置一些属性。

有个问题:DispatcherServlet 默认拦截“/”,MyServlet 拦截“/xs/*”,MyServlet2 拦截“/xs/myservlet”,那么在我们访问 http://localhost:8080/xs/myservlet 的时候系统会怎么处理呢?如果访问 http://localhost:8080/xs/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做很多修改,并非只是UrlMappings。

七、Spring Boot Servlet 使用的更多相关文章

  1. spring boot servlet 注入

    spring boot 注入servlet的方法是借助ServletRegistrationBean这个类 例子如下: 先建一个servlet import java.io.IOException; ...

  2. Spring Boot Servlet

    上一篇我们对如何创建Controller 来响应JSON 以及如何显示数据到页面中,已经有了初步的了解. Web开发使用 Controller 基本上可以完成大部分需求,但是我们还可能会用到 Serv ...

  3. 20. Spring Boot Servlet【从零开始学Spring Boot】

    转载:http://blog.csdn.net/linxingliang/article/details/52069482 Web开发使用 Controller 基本上可以完成大部分需求,但是我们还可 ...

  4. (20)Spring Boot Servlet【从零开始学Spring Boot】

    Web开发使用 Controller 基本上可以完成大部分需求,但是我们还可能会用到 Servlet.Filter.Listener.Interceptor 等等. 当使用Spring-Boot时,嵌 ...

  5. spring boot servlet、filter、listener

    http://blog.csdn.net/catoop/article/details/50501686

  6. 3. Spring Boot Servlet

    转自:https://blog.csdn.net/catoop/article/details/50501686

  7. Spring Boot 2 实战:如何自定义 Servlet Filter

    1.前言 有些时候我们需要在 Spring Boot Servlet Web 应用中声明一些自定义的 Servlet Filter 来处理一些逻辑.比如简单的权限系统.请求头过滤.防止 XSS 攻击等 ...

  8. Spring Boot 实战:如何自定义 Servlet Filter

    1.前言 有些时候我们需要在 Spring Boot Servlet Web 应用中声明一些自定义的 Servlet Filter来处理一些逻辑.比如简单的权限系统.请求头过滤.防止 XSS 攻击等. ...

  9. 快速开发架构Spring Boot 从入门到精通 附源码

    导读 篇幅较长,干货十足,阅读需花费点时间.珍惜原创,转载请注明出处,谢谢! Spring Boot基础 Spring Boot简介 Spring Boot是由Pivotal团队提供的全新框架,其设计 ...

随机推荐

  1. SSM框架搭建(Spring+SpringMVC+MyBatis)与easyui集成并实现增删改查实现

    一.用myEclipse初始化Web项目 新建一个web project: 二.创建包 controller        //控制类 service //服务接口 service.impl //服务 ...

  2. hibernate flushMode 错误

    1 十一月 15, 2017 10:13:36 上午 org.apache.struts2.dispatcher.Dispatcher error 2 严重: Exception occurred d ...

  3. SQLSERVER实现更改表名,更改列名,更改约束代码

    1.修改表名 格式:sp_rename tablename,newtablename ? 1 sp_rename tablename,newtablename 2.修改字段名 格式:sp_rename ...

  4. 【分享】jQuery无插件实现 鼠标拖动图片切换 功能

    前言 我就想随便叨逼叨几句,爱看就看几句,不爱看就直接跳过看正文就好啦~ 这个方法是仿写页面时我自己研究出来,可能有比我更简单的方法. 但我不管,因为我没查我不知道,我就觉得我的最好啦,耶耶耶~ 效果 ...

  5. mysql timeout

    (待更新整理) 因为最近遇到一些超时的问题,正好就把所有的timeout参数都理一遍,首先数据库里查一下看有哪些超时: root@localhost : test 12:55:50> show ...

  6. ASP.NET Core 认证与授权[6]:授权策略是怎么执行的?

    在上一章中,详细介绍了 ASP.NET Core 中的授权策略,在需要授权时,只需要在对应的Controler或者Action上面打上[Authorize]特性,并指定要执行的策略名称即可,但是,授权 ...

  7. GraphicsMagick的命令行使用示例

    GraphicsMagick是从 ImageMagick 5.5.2 分支出来的,但是现在他变得更稳定和优秀,GM更小更容易安装.GM更有效率.GM的手册非常丰富GraphicsMagick的命令与I ...

  8. 独家分析:安卓“Janus”漏洞的产生原理及利用过程

    近日,Google在12月发布的安卓系统安全公告中披露了一个名为"Janus"安卓漏洞(漏洞编号:CVE-2017-13156).该漏洞可以让攻击者绕过安卓系统的signature ...

  9. mysql优化sql语句的方法

    1.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引. 2.应尽量避免在 where 子句中使用!=或<>操作符,否则将引擎放弃使用索 ...

  10. js 实现div模块的截图并下载功能(可制作长图)

    当需要实现html页面部分模块截图并具有保存图片功能时,前台直接生成截图并下载会方便的多.多的不说,直接看代码首先我们需要引入2个js文件: <script type="text/ja ...