【问题标题】:Spring MVC viewController haven't the same behavior depending on template engine根据模板引擎,Spring MVC viewController 的行为不同
【发布时间】:2016-05-01 19:10:15
【问题描述】:

我正在通过 Spring Boot Starters (1.3.2) 使用 Spring MVC,我看到了关于我使用的模板引擎的行为差异。

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // template file 
        registry.addViewController("/index").setViewName("index");
        // static file
        registry.addViewController("/login").setViewName("login.html");
    }
}

如果我使用Freemarker 作为模板引擎,Spring mvc 将从resources/static 获取文件以获取/login 并在resources/templates 获取文件以获取/index

然而,如果我使用 Thymeleaf 作为模板引擎,Spring 将从 resources/templates 获取所有文件(loginindex)。

【问题讨论】:

    标签: spring-mvc spring-boot freemarker thymeleaf


    【解决方案1】:

    据我所知,这条路径取决于应用程序属性。默认情况下:

    #for freemaker
    spring.freemarker.template-loader-path=classpath:/templates/
    
    #for thymeleaf
    spring.thymeleaf.prefix=classpath:/templates/
    spring.thymeleaf.suffix=.html
    

    您可以找到here 的常见应用程序属性的完整列表。

    视图控制器不会改变行为。当您输入 url 时,Spring 会寻找具有合适请求映射的 Controller 或 ViewController 的方法。如果找到方法,则 Spring 调用它。之后,控制器的方法将视图名称作为字符串返回,Spring 会请求一个名为ViewResolver 的特殊bean 来查找具有该名称的视图。

    由于每个模板引擎都有自己的ViewResolver,并且任何ViewResolver 都有自己的设置(正如我上面所说的),他们正在不同的地方寻找模板。

    例如,您正在使用 Thymeleaf 并作为 url 输入类似:localhost:8080/index。首先,spring 会找到映射到index 的控制器方法或视图控制器。之后,控制器将返回字符串index。 Spring 将要求 Teamleaf 视图解析器找到此视图。根据默认设置,视图解析器会在视图名称前添加classpath:/templates/,在视图名称后添加.html,之后会尝试使用该名称打开文件。

    【讨论】:

    • 我不覆盖任何属性。我在质疑 viewController 的行为,当我更改模板引擎时该行为发生了变化。
    猜你喜欢
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 2014-05-15
    • 1970-01-01
    • 2020-08-27
    • 2017-10-19
    • 2015-08-18
    相关资源
    最近更新 更多