SpringBoot学习笔记(四)—— Servlet

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/u012211603/article/details/83328849

一、传统的Servlet结合SpringBoot。

1、创建一个自己的Servlet继承HttpServlet:

@WebServlet(urlPatterns = "/my/servlet")   // URL映射
public class MyServlet extends HttpServlet {  //Servlet3.0规定需要继承HttpServlet
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().println("Fight for Java");
    }
}

2、在启动类上添加Servlet包扫描注解:

@ServletComponentScan(basePackages = "com.orcas.base.web.servlet")  
// Servlet注册: 扫描MyServlet所在包下的所有组件加以注册
public class BaseApplication {

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

3、启动后可以在控制台看到:
Servlet com.orcas.base.web.servlet.MyServlet mapped to [/my/servlet]

4、浏览器访问该路径后成功获得:
在这里插入图片描述

二、异步Servlet (3.0)

1、首先需要把asyncSupported设置为true,表明Servlet支持异步处理。
2、获得异步上下文AsyncContext
3、启用新线程执行耗时操作。
4、手动触发完成。

@Slf4j
@WebServlet(urlPatterns = "/my/servlet", // URL映射
        asyncSupported = true) // 同步支持默认为false,这里设置为true
public class MyServlet extends HttpServlet { //Servlet3.0规定需要实现HttpServlet接口

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 异步上下文
        AsyncContext asyncContext = req.startAsync();
        // Runnable
        asyncContext.start(() -> {
            try {
                resp.getWriter().println("Fight for Java");
                // 触发完成 : 异步需要显式地表明已经完成。
                asyncContext.complete();

            } catch (IOException e) {
                log.error("IO异常: {}", e);
            }
        });

    }
}

======================================================
to be continued。。。

猜你喜欢

转载自blog.csdn.net/u012211603/article/details/83328849
今日推荐