内嵌式 Tomcat 配置

依赖

可能需要用到 jsp 的依赖

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat.embed/tomcat-embed-core -->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-core</artifactId>
    <version>9.0.37</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat.embed/tomcat-embed-jasper -->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <version>9.0.37</version>
</dependency>

启动类

package io.xuqu;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;

import java.io.File;

public class Application {
    public static void main(String[] args) throws LifecycleException {
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8080);
        tomcat.getConnector();

        String contextPath = "";
        String docBase = new File("src/main/webapp").getAbsolutePath();
        Context context = tomcat.addWebapp(contextPath, docBase);

        String webAppMount = "/WEB-INF/classes";
        String base = new File("target/classes").getAbsolutePath();
        String internalPath = "/";
        StandardRoot standardRoot = new StandardRoot(context);
        DirResourceSet dirResourceSet = new DirResourceSet(standardRoot, webAppMount, base, internalPath);
        standardRoot.addPreResources(dirResourceSet);

        context.setResources(standardRoot);

        tomcat.start();
        tomcat.getServer().await();
    }
}

注解 Servlet

package io.xuqu;

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("/hello")
public class MainServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
        throws IOException, ServletException {
        req.getRequestDispatcher("/view/hello.jsp").forward(req, resp);
    }
}
.
├── webapp
    ├── view
    │   └── hello.jsp
    └── WEB-INF

Copyright: 采用 知识共享署名4.0 国际许可协议进行许可

Links: https://blog.imoyb.com/archives/embbed-tomcat-test