使用jax-rs的动态Web项目的相对路径

时间:2017-07-20 08:51:14

标签: java jax-rs

我想在我的代码中使用app_config文件,并希望在服务器中启动项目时加载它。

package test.controller;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.mysql.cj.core.util.StringUtils;

import test.config.AppConfig;
import test.connection.jdbc.JDBCConnection;

@ApplicationPath("webapp")
public class RestApplication extends Application{

    public static final String CONFIG_FILE = "C:\\Users\\chakrabo\\eclipse-workspace\\HelloWorld\\config\\src\\main\\resources\\app-config.xml";
    private static ObjectMapper objectMapper = new XmlMapper();
    public static AppConfig appConfig = getConfig();
    public static Connection con = JDBCConnection.getConnection(appConfig.getDbUrl(), 
            appConfig.getUsername(), appConfig.getPassword());

    private static AppConfig getConfig() {
        try {
            AppConfig config = objectMapper.readValue(
            StringUtils.toString(Files.readAllBytes(Paths.get(CONFIG_FILE))), AppConfig.class);
            return config;
        } catch(Exception e) {
            System.out.println("RestApplication : getConfig " +e.getMessage());
            return null;
        }
    }


}

通过实际路径,我可以阅读此app-config文件。但我不知道如何根据相对路径阅读它。

enter image description here

上下文应该是HelloWorld(项目名称),但它不起作用。即使我把这个配置文件夹放在webcontent和WEB-INF中,它仍然说文件未找到异常。

任何人都可以帮助我。

2 个答案:

答案 0 :(得分:0)

要获取文件的路径,请尝试使用ServletContext。

在Application中创建一个字段(全局实例变量):

@Context
ServletContext servletContext;

然后使用

String path = servletContext.getRealPath("/WEB-INF/app-config.xml");

这使用了JAX-RS的内置依赖注入机制。

您需要这样的Servlet API

<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.0.1</version>
  <scope>provided</scope>
</dependency>

答案 1 :(得分:0)

您可以使用以下内容:

RestApplication.getClass().getClassLoader().getResourceAsStream("app-config.xml")));

通过此操作,您可以从src/main/resources文件夹中加载文件

相关问题