小编典典

为什么从WEB-INF文件夹内部无法加载POSModel文件?

tomcat

我将Spring MVC用于我的Web项目。我将模型文件放在WEB-INF目录中

String taggerModelPath = "/WEB-INF/lib/en-pos-maxent.bin";
String chunkerModelPath = "/WEB-INF/lib/en-chunker.bin";

POSModel model = new POSModelLoader()
.load(new File(servletContext.getResource(taggerModelPath).toURI().getPath()));

在Windows环境下工作。但是,当我将其部署到远程Linux服务器上时,出现错误

HTTP状态500-请求处理失败;嵌套的异常是opennlp.tools.cmdline.TerminateToolException:POS
Tagger模型文件不存在!路径:/localhost/nlp/WEB-INF/lib/en-pos-maxent.bin

访问文件资源的最佳方法是什么?谢谢


阅读 373

收藏
2020-06-16

共1个答案

小编典典

假设您使用的是OpenNLP 1.5.3,则应该使用另一种加载资源文件的方式,该方式不通过URI转换使用“硬”路径引用。

给定一个环境,其中WEB-INF目录中resources存在另一个包含您的OpenNLP模型文件的目录,您的代码片段应编写如下:

String taggerModelPath = "/WEB-INF/resources/en-pos-maxent.bin";
String chunkerModelPath= "/WEB-INF/resources/en-chunker.bin";

POSModel model = new POSModelLoader().load(servletContext.getResourceAsStream(taggerModelPath));

有关ServletContext#getResourceAsStream的信息,请参见Javadoc;

重要提示

可悲的是,您的代码还有其他问题。OpenNLP类POSModelLoader仅供 内部
使用,请参阅POSModelLoader的官方Javadoc :

为命令行工具加载POS Tagger模型。

注意: 请勿使用此类,仅供内部使用!

因此,POSModel在Web上下文中加载a应该做的不同:通过该类的可用构造函数之一。您可以这样重新编写上面的代码片段:

try {
    InputStream in = servletContext.getResourceAsStream(taggerModelPath);
    POSModel posModel;
    if(in != null) {
        posModel = new POSModel(in);

        // from here, <posModel> is initialized and you can start playing with it...
        // ...
    }
    else {
        // resource file not found - whatever you want to do in this case
    }
}
catch (IOException | InvalidFormatException ex) {
    // proper exception handling here... cause: getResourcesAsStream or OpenNLP...
}

这样,您就符合OpenNLP API的要求,同时可以进行适当的异常处理。而且,如果模型文件的资源路径引用仍然不清楚,您现在可以使用调试器。

希望能帮助到你。

2020-06-16