SpringBoot - 使用Servlet

一、在SpringBoot中使用Servlet

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); }
}

 

訪問:http://localhost:8080/onespring

 

後臺打印:app

 

 

1.二、另外一種初始化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/twoide

 

後臺打印:url

 

相關文章
相關標籤/搜索