如何在SpringBoot中使用Servlet

x33g5p2x  于2021-11-27 转载在 Spring  
字(1.6k)|赞(0)|评价(0)|浏览(488)

一、注解方式

1.1、创建SpringBoot Web工程

1.2、创建Servlet类并添加@WebServlet注解

继承HttpServlet类并且重写doGet和doPost方法
用注解的方式使用Servlet:在Servlet类上加@WebServlet注解

  1. //相当于web.xml配置文件<servlet>标签里的内容
  2. @WebServlet(urlPatterns = "/myServlet")
  3. public class MyServlet extends HttpServlet {
  4. @Override
  5. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  6. //向页面中打印SpringBoot Servlet字符串
  7. response.getWriter().print("SpringBoot Servlet");
  8. response.getWriter().flush();
  9. //关闭流
  10. response.getWriter().close();
  11. }
  12. @Override
  13. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  14. doGet(request,response);
  15. }
  16. }

1.3、在引导类上添加@ServletComponentScan注解

@ServletComponentScan:扫描指定包下的注解

  1. @SpringBootApplication
  2. @ServletComponentScan(basePackages = "com.why.servlet")
  3. public class Ch06SpringbootServletApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(Ch06SpringbootServletApplication.class, args);
  6. }
  7. }

测试:

二、配置类方式

2.1、创建SpringBoot工程

2.2、创建Servlet类

使用配置类方式就无需加@WebServlet注解了

  1. public class MyServlet extends HttpServlet {
  2. @Override
  3. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  4. response.getWriter().print("SpringBoot Servlet");
  5. response.getWriter().flush();
  6. response.getWriter().close();
  7. }
  8. }

2.3、创建Servlet配置类

  1. @Configuration//声明这个类是配置类
  2. public class ServletConfig {
  3. @Bean//注册一个Servlet对象并交给Spring容器管理
  4. public ServletRegistrationBean myServletRegistrationBean(){
  5. ServletRegistrationBean srb = new ServletRegistrationBean(new MyServlet(),"/myServlet2");
  6. return srb;
  7. }
  8. }

测试:

相关文章