Spring Boot Servlet 您所在的位置:网站首页 骁龙845好还是麒麟970好 Spring Boot Servlet

Spring Boot Servlet

2024-01-21 01:43| 来源: 网络整理| 查看: 265

上一篇我们对如何创建Controller 来响应JSON 以及如何显示数据到页面中,已经有了初步的了解。 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 接口直接注册。

通过代码注册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注解) * * @return * @author SHANHY * @create 2016年1月6日 */ @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 * * @author 单红宇(365384722) * @myblog http://blog.csdn.net/catoop/ * @create 2016年1月6日 */ //@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()>>>>>>>>>doGet2()>>>>>>>>>doPost2()


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有