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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值