spring boot 十五 (servlet)

虽然 spring boot 中 直接使用servlet 实现的地方越来越少了,但是spring boot 依然提供了两种方式:

方法一 (基于 spring boot @WebServlet 注解扫描):

(记得不能要super.doGet()和super.doPost 否则会报错)

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

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("servlet  hello");
        resp.getWriter().flush();
        resp.getWriter().close();
    }

第二步在application上添加 servlet 扫描注解

@SpringBootApplication
@ServletComponentScan
public class DemoApplication {

方式二 (使用 @Bean 配置)

不需要 @WebServlet 注解

public class HelloServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("servlet  hello");
        resp.getWriter().flush();
        resp.getWriter().close();
    }
}

第二步 在application 或者在 @Configuration 类下 填写下面 方法 都可以完成:

@SpringBootApplication
public class DemoApplication {
	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
	@Bean
	public ServletRegistrationBean registrationBean(){
		ServletRegistrationBean registrationBean = new ServletRegistrationBean(new HelloServlet(),"/test1/hello");
		return registrationBean;
	}
}

或者:

@Configuration
public class WebConfig  extends WebMvcConfigurationSupport {

    @Bean
    public ServletRegistrationBean registrationBean(){
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new HelloServlet(),"/test1/hello");
        return registrationBean;
    }

猜你喜欢

转载自blog.csdn.net/zhanglinlang/article/details/88422560