在springboot中创建普通servlet和异步servlet

在springboot中创建普通servlet和异步servlet

    • 普通servlet
    • 异步servlet

在spring中注册一个Servelt的方式我所知有三种方式:Servlet注解、Spring Bean、RegistrationBean
这里介绍第一种方式

普通servlet

1.首先引入web的maven依赖


   org.springframework.boot
   spring-boot-starter-web

2.实现一个servlet编写

public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
    				throws ServletException, IOException {
        resp.getWriter().write("Hello World!");
    }
}

3.在这个servlet上添加@WebServlet注解,并添加上映射路径

@WebServlet(urlPatterns = "/my/servlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
    				throws ServletException, IOException {
        resp.getWriter().write("Hello World!");
    }
}

4.在springboot启动类中添加注解@ServletComponentScan,扫描到你所实现的servlet的包路径

@SpringBootApplication
@ServletComponentScan(basePackages = "com.ice.DiveSpringBoot.web.servlet") //扫描servlet组件所在的包
public class DiveSpringBootApplication {

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

}

异步:servlet 3.0
非阻塞: servlet 3.1


异步servlet

修改上面的3中的代码

@WebServlet(urlPatterns = "/my/asyncServlet",asyncSupported = true) // asyncSupported 表示本Servelt是否支持异步
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
    				throws ServletException, IOException {
        
        // resp.getWriter().write("Hello World!");
        AsyncContext asyncContext = req.startAsync();
        asyncContext.start(() -> {
            try {
            
                resp.getWriter().write("async : hello world!");  
                // 异步操作时候最终这里要进行结束,在这之前可以多次调用request和response:
                // eg: asyncContext.getResponse().getWriter().write("hello");
                asyncContext.complete(); 
                
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
                    
    }
}

你可能感兴趣的:(Spring,Boot)