简体   繁体   English

为什么我得到了看似简单的StringTemplate代码的NullPointerException?

[英]Why do I get a NullPointerException with seemingly simple StringTemplate code?

I'd like to use StringTemplate 4 to render views in my Google App Engine app. 我想使用StringTemplate 4在我的Google App Engine应用程序中呈现视图。

In my Controller (I'm using Slim3 MVC framework if it matters), I have this code: 在我的控制器中(如果重要,我正在使用Slim3 MVC框架),我有以下代码:

STGroup group = new STGroupDir("templates/default",'$','$');
ST stPage = group.getInstanceOf("page");
stPage.add("title", "Welcome to my Page!");
stPage.add("title_h1", "So glad you came!");
response.getWriter().print(stPage.render());
return null;

I have a single ST file named page.st in the directory war/templates/default 我在目录war/templates/default只有一个名为page.st ST文件

When I run this code, I get the following NullPointerException . 当我运行此代码时,我得到以下NullPointerException When viewing the ST code online, it appears to be related to the path to the file. 在线查看ST代码时,它似乎与文件的路径有关。 The path to the template file is accessible via web browser by navigating to it. 模板文件的路径可通过浏览器通过Web浏览器访问。

Here's the relevant part of the exception: 这是例外的相关部分:

java.lang.NullPointerException
    at org.stringtemplate.v4.STGroup.loadTemplateFile(STGroup.java:656)
    at org.stringtemplate.v4.STGroupDir.loadTemplateFile(STGroupDir.java:176)
    at org.stringtemplate.v4.STGroupDir.load(STGroupDir.java:136)
    at org.stringtemplate.v4.STGroup.lookupTemplate(STGroup.java:230)
    at org.stringtemplate.v4.STGroup.getInstanceOf(STGroup.java:165)

Edit: 编辑:

I figured out my file was formatted improperly. 我发现我的文件格式不正确。 If your page.st file is a valid format, you will not get the NullPointerException . 如果page.st文件是有效格式,则不会获得NullPointerException Here is an example of a valid page.st file. 这是有效的page.st文件的示例。 Above, I have added what it takes to render this page from a servlet. 上面,我添加了从servlet渲染此页面所需的操作。

page(title,title_h1)::=<<
<!DOCTYPE html>
    <head>
      <title>$title$</title>
    </head>
    <body>
    <h1>$title_h1$</h1>
    </body>
</html>
>>

It turns out, the format of my page.st file was incorrect. 事实证明,我的page.st文件格式不正确。 In this case, you get the NullPointerException . 在这种情况下,您将获得NullPointerException I have updated my question to include a proper format for page.st. 我已经更新了我的问题,以包括page.st的正确格式。

只要ST文件中存在错误,并且实例被称为Null Pointer Exception(空指针异常),则总是可以诊断ST文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM