Servlet上下文获取实际路径返回null

时间:2016-09-22 12:51:53

标签: java jsf

我试图从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();
    }

}

1 个答案:

答案 0 :(得分:-1)

请查看

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