Spring Boot 使用Servlet与异步Servlet-五

建立spring-boot项目

<dependencies>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starterartifactId>
		dependency>

		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-webartifactId>
		dependency>

		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-testartifactId>
			<scope>testscope>
		dependency>
	dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.bootgroupId>
				<artifactId>spring-boot-maven-pluginartifactId>
			plugin>
		plugins>
	build>

Servlet

/**
 * WebServlet使用注解声明与映射
 */
@WebServlet(urlPatterns = "/my/servlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                resp.getWriter().println("helloWorld");

    }
}

Application.java

//注册Servlet
@ServletComponentScan(basePackages = "com.ghgcn.driverspringboot.web.servlet")
@SpringBootApplication
public class DriverSpringBootApplication {

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

}

访问
Spring Boot 使用Servlet与异步Servlet-五_第1张图片

异步

package com.ghgcn.driverspringboot.web.servlet;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * WebServlet声明
 * asyncSupported打开支持异步
 */
@WebServlet(urlPatterns = "/my/async",asyncSupported = true)
public class MyAsyncServlet extends HttpServlet {

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

        //获取异步的上下文
        AsyncContext asyncContext = req.startAsync();

        /**
         * 在子线程中执行
         */
        asyncContext.start(()->{
            try {
                resp.getWriter().println("this is async.");
                //手动触发完成
                asyncContext.complete();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

    }
}


其中WebServlet要打开
*/
boolean asyncSupported() default false; 支持,默认是false不支持的

你可能感兴趣的:(SpringBoot)