我正在尝试Java EE servlet教程代码示例 https://javaee.github.io/tutorial/servlets013.html(Servlet 4.0)
首先,它可以与Spring Boot + Tomcat ,Spring boot + Jetty 和 GlassFish 一起使用。 但是,当我尝试使用Spring Boot + Undertow 时,它失败并显示错误:
“处于异步模式的流尚未准备好进行IO操作”
这是我的gradle设置:
buildscript {
ext {
springBootVersion = '2.0.3.RELEASE'
}
// ext ['undertow.version'] = '2.0.10.Final' the latest version, does not work either
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
sourceCompatibility = 1.8
targetCompatibility = 1.8
configurations {
// not to use tomcat from spring boot
compile.exclude module: "spring-boot-starter-tomcat"
}
dependencies {
compile group: 'javax.servlet', name: 'javax.servlet-api', version: '4.0.1'
compile('org.springframework.boot:spring-boot-starter-web')
// explicitly choose undertow
compile("org.springframework.boot:spring-boot-starter-undertow")
}
这是我的春季靴子主班
@SpringBootApplication
@ServletComponentScan // scan and load all servlets with @WebServlet annotation
public class HelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldApplication.class, args);
}
}
这是教程示例代码(https://javaee.github.io/tutorial/servlets013.html)
@WebServlet(urlPatterns={"/asyncioservlet"}, asyncSupported=true)
public class AsyncIOServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException {
final AsyncContext acontext = request.startAsync();
final ServletInputStream input = request.getInputStream();
input.setReadListener(new ReadListener() {
byte buffer[] = new byte[4*1024];
StringBuilder sbuilder = new StringBuilder();
@Override
public void onDataAvailable() {
try {
do {
int length = input.read(buffer);
sbuilder.append(new String(buffer, 0, length));
} while(input.isReady());
} catch (IOException ex) { }
}
@Override
public void onAllDataRead() {
try {
acontext.getResponse().getWriter()
.write("...the response...");
} catch (IOException ex) { }
acontext.complete();
}
@Override
public void onError(Throwable t) { }
});
}
}