假设我在Jetty库中有以下嵌入式Java servlet的示例-是否可以使用Tomcat API库进行等效操作?
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.AbstractHandler; public class HelloHandler extends AbstractHandler { public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); response.getWriter().println("<h1>Hello World</h1>"); } public static void main(String[] args) throws Exception { Server server = new Server(8080); server.setHandler(new HelloHandler()); server.start(); server.join(); } }
Tomcat7嵌入式等效项如下所示:
public class TinyTomcat7Embedded { public static void main(String[] args) { Tomcat tomcat = new Tomcat(); tomcat.setPort(8080); File baseDir = new File("tomcat"); tomcat.setBaseDir(baseDir.getAbsolutePath()); File applicationDir = new File(baseDir + "/webapps", "/ROOT"); if (!applicationDir.exists()) { applicationDir.mkdirs(); } try { Context appContext = tomcat.addWebapp("/", "ROOT"); // A Jetty AbstractHandler is an HttpServlet here: Tomcat.addServlet(appContext, "helloWorldServlet", new HttpServlet() { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("<h1>Hello World</h1>"); } }); appContext.addServletMapping("/helloworld", "helloWorldServlet"); tomcat.start(); System.out.println("Tomcat server: http://" + tomcat.getHost().getName() + ":" + 8080 + "/"); tomcat.getServer().await(); } catch (ServletException e) { e.printStackTrace(); } catch (LifecycleException e) { e.printStackTrace(); } } }
将这些依赖项添加到您的pom.xml中:
<!-- Eclipse Java Compiler --> <dependency> <groupId>org.eclipse.jdt.core.compiler</groupId> <artifactId>ecj</artifactId> <version>3.7.1</version> </dependency> <!-- Tomcat Embedded --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-core</artifactId> <version>7.0.26</version> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-logging-juli</artifactId> <version>7.0.26</version> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-logging-log4j</artifactId> <version>7.0.26</version> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <version>7.0.26</version> </dependency>