从 Undertow 1.2.5 示例代码修改:
此 URL 的可运行项目将于 2015 年 6 月 10 日到期:
https ://www.hightail.com/download/bXBaTXRRaFJQb0xIRHRVag
package servlet;
import javax.servlet.ServletException;
import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.server.HttpHandler;
import io.undertow.server.handlers.PathHandler;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.DeploymentManager;
import static io.undertow.servlet.Servlets.defaultContainer;
import static io.undertow.servlet.Servlets.deployment;
import static io.undertow.servlet.Servlets.servlet;
/**
* @author Stuart Douglas
*/
public class ServletServer {
public static final String MYAPP = "/myapp";
public static void main(final String[] args) {
try {
DeploymentInfo servletBuilder = deployment()
.setClassLoader(ServletServer.class.getClassLoader())
.setContextPath(MYAPP)
.setDeploymentName("doesnotmatter.war")
.addServlets(
servlet("MessageServletA", MessageServletA.class)
.addInitParam("message", "Hello AAA\n")
.addMapping("/msgA/*"),
servlet("MessageServletB", MessageServletB.class)
.addInitParam("message", "Hello BBB\n")
.addMapping("/msgB/*"),
servlet("MessageServletC", MessageServletC.class)
.addInitParam("message", "Hello CCC\n")
.addMapping("/msgC/*")
);
DeploymentManager manager = defaultContainer().addDeployment(servletBuilder);
manager.deploy();
HttpHandler servletHandler = manager.start();
PathHandler path = Handlers.path(Handlers.redirect(MYAPP))
.addPrefixPath(MYAPP, servletHandler);
Undertow server = Undertow.builder()
.addHttpListener(8080, "localhost")
.setHandler(path)
.build();
server.start();
} catch (ServletException e) {
throw new RuntimeException(e);
}
}
}
请在 shell 中使用以下命令进行测试:
# Runs in background
java -cp target/undertowservlet-jar-with-dependencies.jar servlet.Servletrver &
curl http://localhost:8080/myapp/msgA/
curl http://localhost:8080/myapp/msgB/
curl http://localhost:8080/myapp/msgC/