• SpringBoot中如何集成Servlet呢?


    转自:

    SpringBoot中如何集成Servlet呢?

    下文笔者将讲述两种SpringBoot集成Servlet的方法,如下所示:

    实现思路:
        方式1:
           使用全注解的方式开发
    	    1.1 在启动类上面加上注解 @ServletComponentScan 
    		1.2 编写Servlet程序,并在Servlet程序上加上注解 @WebServlet(name="testServlet1",urlPatterns = "/test")
     	方式2:
    	   直接编写一个@Configuration类
    	   将Servlet程序使用ServletRegistrationBean注册到Springboot中
    

    例1:

    //启动类上加入Servlet扫描注解
    @SpringBootApplication
    @ServletComponentScan
    public class SpringbootservletApplication {
        public static void main(String[] args) {
            SpringApplication.run(SpringbootservletApplication.class, args);
        }
    }
    
    //编写Servlet类
    @WebServlet(name="testServlet1",urlPatterns = "/test")
    public class TestServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            System.out.println("java265.com 提醒你 -servlet已经开始运行");
        }
    }
    -----采用以上方式编写代码后,我们可以使用
    http://localhost:8080/test访问servlet了
    

    例2:

    @SpringBootApplication
    public class SpringbootservletApplication {
        public static void main(String[] args) {
            SpringApplication.run(SpringbootservletApplication.class, args);
        }
    }
    
    //编写servlet
    public class TestServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            System.out.println("java265.com 提醒你 -servlet已经开始运行");
        }
    }
    
    //编写configuration类
    package com.java265;
    import com.adeal.servlet.TestServlet;
    import org.springframework.boot.web.servlet.ServletRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    @Configuration
    public class ServletConfig {
        /*
        * 多个Servlet 需实例化多个ServletRegistrationBean实例
        * */
        @Bean
        public ServletRegistrationBean getServletRegistrationBean() {
            ServletRegistrationBean bean = new ServletRegistrationBean(new TestServlet());
    		//Servlet既可以使用 test01也可以使用test02访问
            bean.addUrlMappings("/test02"); 
            bean.addUrlMappings("/test01");
            return bean;
        }
    }
    -------编写以上代码后,我们可以使用----
    http://localhost:8080/test01 访问servlet了
    http://localhost:8080/test02 访问servlet了
    

  • 相关阅读:
    CabloyJS 4.22重磅推出弹出式页面交互风格
    Java毕设项目——网上宠物店管理系统(java+SSM+Maven+Mysql+Jsp)
    敏捷开发流程图Scrum
    运维就业现状怎么样?技能要求高吗?
    索尼 toio™ 应用创意开发征文|创新音乐创作工具的诞生
    Java实现基数排序
    开发过程中那些包应该放到devDependencies,dependencies
    【设计模式】访问者模式
    国开现代汉语专题,形考答案形考任务
    js+贝塞尔曲线+animate动画
  • 原文地址:https://blog.csdn.net/qq_25073223/article/details/127897189