SpringBoot之整合Servlet

Servlet 相信大家都不陌生,假如我在springboot项目里面需要使用 servlet怎么办呢,springboot项目webxml都没有了。

这里我就给大家展示两种 springboot 整合 servlet的方法,这里使用的 spring 项目配置沿用之前写的那个spring入门的https://blog.****.net/yali_aini/article/details/82865669

1.使用  javax.servlet.annotation.WebServlet 注解

@WebServlet( name = "helloServlet" , urlPatterns = "/hello1")
public class HelloServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedOutputStream bis = new BufferedOutputStream( resp.getOutputStream() );
        bis.write( "<h1>hwllo word</h1>".getBytes() );
        bis.flush();
        bis.close();
    }
}

然后程序启动的时候,使用  @ServletComponentScan 扫描注入到spring 容器里面去。

@SpringBootApplication // spring 启动注解
@ServletComponentScan // servlet 扫描注解
public class Application {

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

}

运行效果:

SpringBoot之整合Servlet

2,使用 org.springframework.boot.web.servlet.ServletRegistrationBean 对象,方法注入,加上注解 @Bean

Servlet 方法:

public class HelloServlet2 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedOutputStream bis = new BufferedOutputStream( resp.getOutputStream() );
        bis.write( "<h1>hwllo word2</h1>".getBytes() );
        bis.flush();
        bis.close();
    }
}

Application.class:

@SpringBootApplication
public class Application2 {

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

    @Bean
    public ServletRegistrationBean setHello1(){
        return new ServletRegistrationBean( new HelloServlet(), "/hello1" );
    }
    // 多个 servlet 则 写多个 方法,方法名不重要,返回对象要是:ServletRegistrationBean
    @Bean
    public ServletRegistrationBean setHello2(){
        return new ServletRegistrationBean( new HelloServlet2() , "/hello2" );
    }
}

这里 注入 Servlet 的时候,如果有多个则写多个。

运行效果:

SpringBoot之整合Servlet