SpringBoot整合Servlet

版权声明:XiangYida https://blog.csdn.net/qq_36781505/article/details/83855831

SpringBoot整合Servlet

方式一、通过注解扫描的方式

  • 1、新建一个Servlet然后使用注解@WebServlet(name=“XXXServlet”,urlPatterns="/XXX")
@WebServlet(name="MyServlet",urlPatterns="/myServlet")
public class MyServlet extends HttpServlet {
   @Override
   protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       System.out.println("hello");
   }
}
  • 2、在启动类前加@ServletConponentScan,在SpringBoot启动时会扫描@WebServlet的注解,
    并将该类实例化
@SpringBootApplication
@ServletComponentScan
public class CrmApplication {
   public static void main(String[] args) {
       SpringApplication.run(CrmApplication.class, args);
   }
}

方式二、通过方法来整合

  • 1、编写Servlet不再需要注解,
  • 2、编写启动类,在启动类中加一个方法
@SpringBootApplication
public class CrmApplication {
  public static void main(String[] args) {
      SpringApplication.run(CrmApplication.class, args);
  }
  //注册servlet
  @Bean
  public ServletRegistrationBean get(){
      ServletRegistrationBean bean=new ServletRegistrationBean(new MyServlet());
      bean.addUrlMappings("/second");
      return bean;
  }
}

猜你喜欢

转载自blog.csdn.net/qq_36781505/article/details/83855831