spring - thymeleaf spring boot templates 子文件夹中的 View

标签 spring spring-mvc spring-boot thymeleaf

我在 Spring Boot 中使用 thymeleaf,并且有几个 View 。我不想将所有 View 保留在同一个文件夹中,默认情况下是 src/main/resources/templates。

是否可以移动 src/main/resources/templates/folder1 中的某些 View ,然后我将传递“folder1/viewname”来访问该页面?

当我尝试http://localhost:8080/folder1/layout1时它没有在 src/main/resources/templates/folder1/中找到我的 html,但是当我将 html 移动到模板主文件夹 src/main/resources/templates/中时,http://localhost:8080/layout1工作得很好。

我的 Controller 类如下所示:

@RequestMapping(value = "{pagename}", method = RequestMethod.GET)
public String mf42_layout1(@PathVariable String pagename) {
    return pagename;
}

所以,我想如果我传递layout1,它会在模板中查找,如果我说“a/layout1”,它会在/layout文件夹中查找

谢谢, 曼尼什

最佳答案

基本上,您的请求映射和 View 名称是解耦的,您只需要注意语法即可。

例如,与

@RequestMapping(value = "/foobar", method = RequestMethod.GET)
public String mf42_layout1() {
    return "layout1";
}

请求http://localhost:8080/foobar将渲染位于 src/main/resources/templates/layout1.html 的模板.

如果您将模板放在子文件夹中,只要您提供正确的 View 路径,它也可以工作:

@RequestMapping(value = "/foobar", method = RequestMethod.GET)
public String mf42_layout1() {
    return "a/layout1";
}

请求http://localhost:8080/foobar将渲染位于 src/main/resources/templates/a/layout1.html 的模板.

您还可以使用 @PathVariable 参数化 url 端点:

@RequestMapping(value = "/foobar/{layout}", method = RequestMethod.GET)
    public String mf42_layout1(@PathVariable(value = "layout") String layout) { // I prefer binding to the variable name explicitely
        return "a/" + layout;
    }

现在请求http://localhost:8080/foobar/layout1将在 src/main/resources/templates/a/layout1.html 中渲染模板并向 http://localhost:8080/foobar/layout2 提出请求将渲染 src/main/resources/templates/a/layout2.html 中的内容

但请注意,正斜杠在 URL 中充当分隔符,因此对于您的 Controller :

@RequestMapping(value = "{pagename}", method = RequestMethod.GET)
public String mf42_layout1(@PathVariable String pagename) {
    return pagename;
}

我的猜测是当你点击http://localhost:8080/a/layout1时pagename 收到“a”并且“layout1”未被捕获。因此 Controller 可能会尝试渲染 src/main/resources/templates/a.html 的内容

Spring MVC reference详细描述了如何映射请求,您应该仔细阅读。

关于spring - thymeleaf spring boot templates 子文件夹中的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42577778/

相关文章:

spring-boot - 如何配置 Zuul 网关(监听两个端口)以拒绝基于端口和 url 组合的请求?

angularjs - 无法通过 Jboss 4.2.2 部署使用 Spring Boot 构建的 Web 应用程序

java - Spring Couchbase 健康指示器

java - @ComponentScan 具有多个配置类 : Annotation Based Configuration

java - Spring MVC 模拟

java - setter 在 Spring 框架中如何工作?

java - 如何处理应用程序运行时数据库关闭时发生的 MySQL CommunicationException

java - 使用 Spring Security Version 5 和 Feign Client(最新版本)时如何处理漏洞 CVE-2018-1258?

java - LocalVariableTableParameterNameDiscoverer 不起作用

java - 无法将 Swagger-ui 链接到我的 Swagger Spring mvc 项目