0

我正在尝试实现应该运行我的 HelloWorld-Servlet 的 EmbeddedTomcat (10.0.4)。我使用的是纯 Java,没有 Spring 等。

虽然在启动时,它无法查找在我的 context.xml 中定义的数据源(Oracle DB):

应用程序无法通过 JNDI 查找获取数据源

我假设在我的嵌入式 Tomcat 中,不会加载 context.xml - 有没有办法将 context.xml 添加到我的嵌入式 Tomcat 中?

上下文.xml

<Context name="app">
    <Resource type="javax.sql.DataSource"
              name="jdbc/myDB"
              factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
              driverClassName="oracle.jdbc.OracleDriver"
              url="jdbc:oracle:thin:@//localhost:1521/orcl"
              username="user"
              password="pass"/>
</Context>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!-- ServletContextListeners -->
    <listener>
        <listener-class>com.mycompany.AppContextListener</listener-class>
    </listener>
    
    <!-- Servlets -->
    <servlet>
        <servlet-name>Hello Word</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.mycompany</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- URL-Mappings -->
    <servlet-mapping>
        <servlet-name>Hello Word</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

应用上下文监听器

public class AppContextListener implements ServletContextListener {

    public static final String DATASOURCE_CONTEXT_NAME = "myDS";
    private final Logger logger = LogManager.getLogger(AppContextListener.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        try {
            InitialContext initContext = new InitialContext();
            DataSource ds = (DataSource) initContext.lookup("java:/comp/env/jdbc/myDB");
            sce.getServletContext().setAttribute(DATASOURCE_CONTEXT_NAME, ds);

        } catch (NamingException e) {
            logger.error("Application was not able to get DataSource through JNDI lookup", e);
        }
    }
}

嵌入式Tomcat

public class EmbeddedTomcat {

    private static final Optional<String> webServerPort = Optional.ofNullable(System.getenv("PORT"));

    public static void main(String[] args) throws Exception, LifecycleException {
        new EmbeddedTomcat().runWebServer();
    }

    public void runWebServer() throws ServletException, LifecycleException, MalformedURLException {
        String contextPath = "/";

        // Create Tomcat Server
        Tomcat tomcatServer = new Tomcat();

        tomcatServer.enableNaming();
        // Bind the port to Tomcat Server
        tomcatServer.setPort(Integer.valueOf(webServerPort.orElse("8090")));

        // Define a web application context
        Context ctx = tomcatServer.addWebapp(contextPath, new File("src/main/webapp").getAbsolutePath());

        // Define and bind web.xml file location
        File configFile = new File(ctx.getDocBase() + "/WEB-INF/web.xml");
        ctx.setConfigFile(configFile.toURI().toURL());

        // Start Tomcat process and wait for requests
        tomcatServer.start();
        tomcatServer.getServer().await();
    }
}
4

0 回答 0