如何在SpringBoot中使用Servlet

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

一、注解方式

1.1、创建SpringBoot Web工程

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

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

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

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

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

@SpringBootApplication
@ServletComponentScan(basePackages = "com.why.servlet")
public class Ch06SpringbootServletApplication {

    public static void main(String[] args) {
        SpringApplication.run(Ch06SpringbootServletApplication.class, args);
    }
}

测试:

二、配置类方式

2.1、创建SpringBoot工程

2.2、创建Servlet类

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

public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().print("SpringBoot Servlet");
        response.getWriter().flush();
        response.getWriter().close();
    }
}

2.3、创建Servlet配置类

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

测试:

相关文章