SpringBoot整合Servlet的两种方式

匿名 (未验证) 提交于 2019-12-03 00:22:01
Maven3.5 JDK1.8 idea SpringBoot2.0.1 
  • 工程pom文件加入Jar包
    <dependency>         <groupId>org.springframework.boot</groupId>         <artifactId>spring-boot-starter-web</artifactId>     </dependency>
@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");     }  }  
@SpringBootApplication @ServletComponentScan   //启动器启动时,扫描本目录以及子目录带有的webservlet注解的 public class FirstServletApplication {      public static void main(String[] args) {         SpringApplication.run(FirstServletApplication.class, args);     } }

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


本文项目源代码 :
GarfieldHuang/JavaDemo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!