从 jar 运行时,Spring Boot 会给出“TemplateInputException:错误解析模板”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27249078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:14:45  来源:igfitidea点击:

Spring Boot gives "TemplateInputException: Error resolving template" when running from jar

springspring-bootthymeleaf

提问by Bob Brown

I have an app that works perfectly when started within IntelliJ or via gradle bootRun.

我有一个在 IntelliJ 中或通过 gradle bootRun 启动时可以完美运行的应用程序。

however, if I do gradle bootRepackage and then try and run the resulting jar, I end up with:

但是,如果我执行 gradle bootRepackage 然后尝试运行生成的 jar,我最终会得到:

2014-12-02 21:46:14.086 ERROR 9839 --- [nio-2014-exec-2] org.thymeleaf.TemplateEngine             : [THYMELEAF][http-nio-2014-exec-2] Exception processing template "/login": Error resolving template "/login", template might not exist or might not be accessible by any of the configured Template Resolvers
2014-12-02 21:46:14.087 ERROR 9839 --- [nio-2014-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Error resolving template "/login", template might not exist or might not be accessible by any of the configured Template Resolvers] with root cause

org.thymeleaf.exceptions.TemplateInputException: Error resolving template "/login", template might not exist or might not be accessible by any of the configured Template Resolvers
    at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:245)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011)
    at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:335)

I can see that the jar has /templates/** contained in it. the content looks OK to me.

我可以看到 jar 中包含 /templates/** 。内容对我来说看起来不错。

One possible(?) factor may be that I use an html page referring to a layout, thus:

一个可能的(?) 因素可能是我使用了一个引用布局的 html 页面,因此:

  layout:decorator="layouts/main"

I can confirm that the file IS in the jar.

我可以确认该文件在 jar 中。

/login is defined thusly:

/login 是这样定义的:

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/login").setViewName("/login");
    registry.addViewController("/").setViewName("/login");
}

and I have spring security configured as:

我将 spring 安全配置为:

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
public void configure(WebSecurity security) {
    security.ignoring().antMatchers("/assets/**");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .csrf().disable();
    http
            .authorizeRequests()
            .antMatchers("/").permitAll()
            .anyRequest().authenticated();
    http
            .formLogin()
            .loginPage("/login")
            .defaultSuccessUrl("/home")
            .failureUrl("/login?error")
            .permitAll()
            .and()
            .logout()
            .invalidateHttpSession(true)
            .logoutSuccessUrl("/login?logout")
            .permitAll();
}
}

I think that's all that might be relevant to this issue...

我认为这就是与这个问题相关的所有内容......

I have seen https://github.com/spring-projects/spring-boot/issues/112and Proper location of Thymeleaf views for Spring(amongst others). These resources notwithstanding, I have not been successful at getting template resolution working.

我已经看到了https://github.com/spring-projects/spring-boot/issues/112Thymeleaf 视图的正确位置 Spring(等等)。尽管有这些资源,我还没有成功地使模板解析工作。

Any suggestions gratefully recieved.

任何建议都非常感谢。

To have come so far with Spring Boot yet to have stumbled at the last hurdle (near-final deployment) is vexatious.

到目前为止,Spring Boot 还没有在最后一个障碍(接近最终部署)中跌跌撞撞,这是令人烦恼的。

回答by user2822874

I had same problem using spring boot with thymeleaf by default configuration. All worked until I have to try .jar

默认情况下,我在使用带有 thymeleaf 的 spring boot 时遇到了同样的问题。一切正常,直到我必须尝试 .jar

message says: ... org.thymeleaf.exceptions.TemplateInputException: Error resolving template "/fragments/footer"

消息说:... org.thymeleaf.exceptions.TemplateInputException:解析模板“/fragments/footer”时出错

I solved playing with / , problem was that they don't need the slash.

我解决了玩 / ,问题是他们不需要斜线。

I Changed this:

我改变了这个:

<footer class="footers" th:replace="/fragments/footer :: footer">

for this:

为了这:

<footer class="footers" th:replace="fragments/footer :: footer">

回答by Bob Brown

The answer seems to be here: https://github.com/spring-projects/spring-boot/issues/1744

答案似乎在这里:https: //github.com/spring-projects/spring-boot/issues/1744

In a nutshell: if a resouce path contains '//', things go awry.

简而言之:如果资源路径包含“//”,事情就会出错。

The fix is to modify application.yml thusly:

解决方法是这样修改 application.yml:

spring:
  thymeleaf:
    prefix: classpath:/templates

(the fix is similar for a .properties file, of course)

(当然,修复与 .properties 文件类似)

The knock-on effect is that all references to templates or whatever need to be preceeded by a slash, as in (Thymeleaf .html file):

连锁效应是所有对模板或任何内容的引用都需要以斜杠开头,如(Thymeleaf .html 文件):

      layout:decorator="/layouts/main"

or (Groovy controller):

或(Groovy 控制器):

@RequestMapping(value = "/home", method = RequestMethod.GET)
def home(Model model, Principal principal) {

    "/home/home"
}

Ithink that spring boot should fix this. Urgently. This is REALLY bad ergonomics that blows up badly, just at the point where one feels like one is nearing final deployment.

认为弹簧靴应该解决这个问题。紧急。这真的是非常糟糕的人体工程学,在人们感觉接近最终部署的时候会严重爆炸。

回答by Michael Hegner

Okay, I found where you have to take a close look. In your Controller classes, when you use @RequestMappingon class, no leading slash (e.g. @RequestMapping("property")). On Method you need a leading slash (e.g. @GetMapping("/list")) and the return value no leading slash (e.g. return "property/list";)

好的,我找到了你必须仔细观察的地方。在您的 Controller 类中,当您使用@RequestMappingon 类时,没有前导斜线(例如@RequestMapping("property"))。在方法上,您需要一个前导斜杠(例如@GetMapping("/list"))并且返回值没有前导斜杠(例如return "property/list";

An Example Snippet

示例代码段

@Controller
@RequestMapping("property")
public class PropertyController {
    @NonNull PropertyService service;

    @GetMapping("/list")
    public String list() {
        return "property/list";
    }
}

回答by firstpostcommenter

I faced the issue when using the spring-boot-starter-thymeleafdependency

我在使用spring-boot-starter-thymeleaf依赖项时遇到了这个问题

So I have used the below dependency instead,

所以我改用了以下依赖项,

        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.9.RELEASE</version>
        </dependency>

回答by Henry Patrick Karugendo

If the above solutions don't work for you, like me,

如果上述解决方案不适合你,比如我,

I changed my Controller to a RestController. It fixed my issue.

我将我的控制器更改为 RestController。它解决了我的问题。

This is, if you are using a Front End App like Angular to talk to your Back-end application.

也就是说,如果您使用像 Angular 这样的前端应用程序与您的后端应用程序对话。

回答by leeCoder

For me there was nothing wrong with my code. All I did was run the mvn cleancommand in my terminal then restart the app again and it worked fine.

对我来说,我的代码没有任何问题。我所做的只是mvn clean在我的终端中运行命令,然后再次重新启动应用程序,它运行良好。

回答by s332401890

spring.thymeleaf.prefix=classpath:/templates/

spring.thymeleaf.prefix=classpath:/templates/

change

改变

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/login").setViewName("/login");
    registry.addViewController("/").setViewName("/login");
}

to

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/login").setViewName("login");
    registry.addViewController("/").setViewName("login");
}

the view name should be Relative path

视图名称应该是相对路径

回答by Paulo Cesar Pengo

After many of tentatives I found a way to resolve my problem about the template error. I dont know if is related to the new version of spring-boot but my change worked.

经过多次尝试,我找到了解决模板错误问题的方法。我不知道是否与 spring-boot 的新版本有关,但我的更改有效。

Every request throught controller instead of returning String "/login", for example, I change to create a object ModelAndView:

每个请求都通过控制器而不是返回字符串“/login”,例如,我更改为创建对象 ModelAndView:

@RequestMapping(value="/login", method=RequestMethod.GET)
public ModelAndView login() {
    ModelAndView mv = new ModelAndView("login");
    return mv;
}

hugs to all.

拥抱所有人。