tomcat使用nio2 connector
2020-06-11 本文已影响0人
mirroru
pom依赖
<properties>
<tomcat.version>9.0.35</tomcat.version>
</properties>
<groupId>com.mirroru</groupId>
<artifactId>TomcatDemp</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-logging-juli</artifactId>
<version>9.0.0.M6</version>
</dependency>
</dependencies>
内嵌方式启动
package com.mirror;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class SimpleWebDemo {
public static void main(String[] args) throws LifecycleException {
Tomcat tomcat = new Tomcat();
tomcat.setBaseDir("temp");
tomcat.setPort(8085);
//must add the following,or it can not be started
//Get the default HTTP connector that is used by the embedded Tomcat.
//tomcat.getConnector();
Connector httpConnector = new Connector("org.apache.coyote.http11.Http11Nio2Protocol");
httpConnector.setPort(8085);
tomcat.getService().addConnector(httpConnector);
String contextPath = "/test";
String docBase = new File(".").getAbsolutePath();
Context context = tomcat.addContext(contextPath, docBase);
HttpServlet servlet = new HttpServlet() {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
writer.println("<html><title>Welcome</title><body>");
writer.println("<h1>Have a Great Day!</h1>");
writer.println("</body></html>");
}
};
String servletName = "Servlet1";
String urlPattern = "/go";
tomcat.addServlet(contextPath, servletName, servlet);
context.addServletMappingDecoded(urlPattern, servletName);
tomcat.start();
tomcat.getServer().await();
}
}
Connector httpConnector = new Connector("org.apache.coyote.http11.Http11Nio2Protocol");
Connector构造函数会调用ProtocolHandler的create方法,基于反射方式创建实例
else {
// Instantiate protocol handler
Class<?> clazz = Class.forName(protocol);
return (ProtocolHandler) clazz.getConstructor().newInstance();
}