SpringBoot - 使用Servlet
1、在SpringBoot中使用Servlet
1.1、使用注解注册Servlet:
/** * SpringBoot使用Servlet */ @WebServlet(name="OneServlet",urlPatterns="/one") public class OneServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("OneServle ..."); super.doGet(req, resp); } }
@SpringBootApplication //在 springBoot 启动时会扫描@WebServlet并实例化 @ServletComponentScan public class AppOne { public static void main(String[] args) { SpringApplication.run(AppOne.class, args); }
}
后台打印:
1.2、另一种初始化Servlet的方法:方法注册
/** * SpringBoot使用Servlet */ public class TwoServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("TwoServle ..."); super.doGet(req, resp); } }
@SpringBootApplication public class AppTwo { public static void main(String[] args) { SpringApplication.run(AppTwo.class, args); } @Bean public ServletRegistrationBean registrationServletBean(){ ServletRegistrationBean bean = new ServletRegistrationBean(new TwoServlet()); bean.addUrlMappings("/two"); return bean; } }
访问:http://localhost:8080/two
后台打印: