zoukankan      html  css  js  c++  java
  • SpringBoot整合Servlet的两种方式

    https://blog.csdn.net/u010508829/article/details/80594003

    SpringBoot整合Servlet的两种方式

        本文环境

        Maven3.5
        JDK1.8
        idea
        SpringBoot2.0.1

         

        工程pom文件加入Jar包

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

      

    1. 注解扫描方式
    - 准备Servlet


    @WebServlet(name = "firstServlet", urlPatterns = "/firstServlet")  //标记为servlet,以便启动器扫描。
    public class FirstServlet extends HttpServlet {

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.getWriter().append("firstServlet");
        }

    }



    - 注册Servlet

    @SpringBootApplication
    @ServletComponentScan   //启动器启动时,扫描本目录以及子目录带有的webservlet注解的
    public class FirstServletApplication {

        public static void main(String[] args) {
            SpringApplication.run(FirstServletApplication.class, args);
        }
    }


    - 访问Servlet

    image
    2. 组建注册方式
    - 准备Servlet

    //这里不需要添加webServlet注解
    public class SecondServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.getWriter().append("SecondServlet");}}


    - 注册Servlet

    @SpringBootApplication
    public class SecondServletApplication {
        public static void main(String[] args) {
            SpringApplication.run(SecondServletApplication.class, args);
        }
        @Bean  //一定要加,不然这个方法不会运行
        public ServletRegistrationBean getServletRegistrationBean() {  //一定要返回ServletRegistrationBean
            ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());     //放入自己的Servlet对象实例
            bean.addUrlMappings("/secondServlet");  //访问路径值
            return bean;}}

     
    - 访问Servlet

    GarfieldHuang/GarfieldHuang
     ————————————————
    版权声明:本文为CSDN博主「黄大胖子」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/u010508829/article/details/80594003

  • 相关阅读:
    MP教程-入门
    [15213] Assembly
    Crack the code interview
    [interview questions] 资料总结
    [Two Sigma OA] Longest Chain
    [Tow Sigma OA] friend cycles
    [security]
    [security] GNUpg
    [coursera] 面试前准备
    [coursera] [design] Hangman
  • 原文地址:https://www.cnblogs.com/xiang--liu/p/11422703.html
Copyright © 2011-2022 走看看