【问题标题】:Servlet context get real path returns null [duplicate]Servlet上下文获取真实路径返回null [重复]
【发布时间】:2017-01-31 01:33:44
【问题描述】:

我正在尝试从 src/main/webapp/ 访问资源

我正在使用 java 1.8.0_101 和 maven 3.0.3

不幸的是,它在一个环境中工作,而不是在另一个 unix 环境中工作

@Named
@ApplicationScoped
public class TestClass {

    private static final String RESOURCE = "/resources/css/test.css";
    private String css = "";

    public void init(@Observes @Initialized(ApplicationScoped.class) ServletContext servletContext) throws IOException {
        String pathString = servletContext.getRealPath(RESOURCE);
        System.out.println("path string: " + pathString);
        byte[] data = Files.readAllBytes(Paths.get(pathString));
        css = new String(data, "UTF-8");
    }

    public String getCss() {
        return css;
    }

    public String format(Object o) {
        if (o instanceof List) {
            List<?> list = (List<?>) o;
            String text = list.toString();
            return text.substring(1, text.length() - 1);
        }
        return o == null ? "" : o.toString();
    }

}

【问题讨论】:

    标签: java jsf


    【解决方案1】:

    请检查一下

    ServletContext servletContext = request.getSession().getServletContext();
    String relativeWebPath = "img/image.png";
    String absoluteDiskPath = servletContext.getRealPath(relativeWebPath);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-27
      • 2017-11-08
      • 1970-01-01
      • 2021-01-27
      相关资源
      最近更新 更多