【问题标题】:Thymeleaf: Generate URL for action in controllerThymeleaf:为控制器中的操作生成 URL
【发布时间】:2018-04-05 15:53:11
【问题描述】:

我开始学习 Spring 框架,在 Spring 之前我使用 Laravel。在 Laravel 中,我们有各种生成 url 的助手,例如:

<a href="{{ action('MyController@someAction') }}">Some url</a>

Thymeleaf 中是否有类似的东西,基本上我想生成一个指向控制器中某些操作的 url,所以如果我更改控制器的映射,所有锚标签的 url 都会更改。

【问题讨论】:

标签: spring spring-boot thymeleaf


【解决方案1】:

有一个用于 Spring Boot 框架的库。您需要在项目中添加它才能动态生成链接。下面给出这个库的gradle依赖。

compile 'org.springframework.boot:spring-boot-starter-hateoas:2.1.4.RELEASE'

我假设您的构建系统是 gradle,但如果您使用的是 maven,请使用以下语法。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-hateoas</artifactId>
    <version>2.1.4.RELEASE</version>
</dependency>

之后,您可以如下动态生成链接。

WebMvcLinkBuilder.linkTo(MyController.class).slash("someAction").withSelfRel().getHref();

【讨论】:

    【解决方案2】:

    Thymeleaf 和 Spring Boot 有很好的关系。 从Spring-initializr 创建 Spring Boot 应用程序 在 Spring Boot pom.xml 中添加以下依赖项

    spring-boot-starter-thymeleaf
    

    WelcomeController.java

    @Controller
    public class WelcomeController {
    
        // inject via application.properties
        @Value("${welcome.message:test}")
        private String message = "Hello World";
    
        @RequestMapping("/")
        public String welcome(Map<String, Object> model) {
            model.put("message", this.message);
            return "welcome";
        }
    
    }
    

    在您的welcome.html 中添加以下内容 src/main/resources/templates/welcome.html

    添加 HTML 定义:

    <html xmlns:th="http://www.thymeleaf.org">
    

    添加到正文中。

    <span th:text="'Message: ' + ${message}"></span>
    

    表格视图

    <tbody>
        <tr th:each="student: ${students}">
          <td> <a th:href="${student.id}"><span  th:text="${student.name}"></span> </a></td>
    
        </tr>
      </tbody>
    

    仅此而已

    【讨论】:

    • 这与我的问题有什么关系。我想知道如何使用 thymeleaf 动态创建指向 MyController@someAction 的 url
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多