`

Spring MVC and Thymeleaf: how to acess data from templates

 
阅读更多

In a typical Spring MVC application, @Controller classes are responsible for preparing a model map with data and selecting a view to be rendered. This model map allows for the complete abstraction of the view technology and, in the case of Thymeleaf, it is transformed into a VariablesMapobject (part of the Thymeleaf template execution context) that makes all the defined variables available to expressions executed in templates.

Spring model attributes

Spring MVC calls the pieces of data that can be accessed during the execution of views model attributes. The equivalent term in Thymeleaf language is context variables.

There are several ways of adding model attributes to a view in Spring MVC. Below you will find some common cases:

Add attribute to Model via its addAttribute method:

    @RequestMapping(value = "message", method = RequestMethod.GET)
    public String messages(Model model) {
        model.addAttribute("messages", messageRepository.findAll());
        return "message/list";
    }

Return ModelAndView with model attributes included:

    @RequestMapping(value = "message", method = RequestMethod.GET)
    public ModelAndView messages() {
        ModelAndView mav = new ModelAndView("message/list");
        mav.addObject("messages", messageRepository.findAll());
        return mav;
    }

Expose common attributes via methods annotated with @ModelAttribute:

    @ModelAttribute("messages")
    public List<Message> messages() {
        return messageRepository.findAll();
    }

As you may have noticed, in all the above cases the messages attribute is added to the model and it will be available in Thymeleaf views.

In Thymeleaf, these model attributes (or context variables in Thymeleaf jargon) can be accessed with the following syntax: ${attributeName}, whereattributeName in our case is messages. This is a Spring EL expression. In short, Spring EL (Spring Expression Language) is a language that supports querying and manipulating an object graph at runtime.

You can access model attributes in views with Thymeleaf as follows:

    <tr th:each="message : ${messages}">
        <td th:text="${message.id}">1</td>
        <td><a href="#" th:text="${message.title}">Title ...</a></td>
        <td th:text="${message.text}">Text ...</td>
    </tr>

Request parameters

Request parameters can be easily accessed in Thymeleaf views. Request parameters are passed from the client to server like:

    https://example.com/query?q=Thymeleaf+Is+Great!

Let’s assume we have a @Controller that sends a redirect with a request parameter:

    @Controller
    public class SomeController {
        @RequestMapping("/")
        public String redirect() {
            return "redirect:/query?q=Thymeleaf Is Great!";
        }
    }

In order to access the q parameter you can use the param. prefix:

    <p th:text="${param.q[0]}" th:unless="${param.q == null}">Test</p>

Two things are important to notice in the above example:

  • ${param.q != null} checks if the parameter q is set
  • Parameters are always string arrays, as they can be multivalued (e.g. https://example.com/query?q=Thymeleaf%20Is%20Great!&q=Really%3F).

Another way to access request parameters is by using the special object #httpServletRequest that gives you direct access to thejavax.servlet.http.HttpServletRequest object:

    <p th:text="${#httpServletRequest.getParameter('q')}" th:unless="${#httpServletRequest.getParameter('q') == null}">Test</p>

Session attributes

In the below example we add mySessionAttribute to session:

    @RequestMapping({"/"})
    String index(HttpSession session) {
        session.setAttribute("mySessionAttribute", "someValue");
        return "index";
    }

Similarly to the request parameters, session attributes can be access by using the session. prefix:

    <div th:text="${session.mySessionAttribute}">[...]</div>

Or by using #httpSession, that gives you direct access to the javax.servlet.http.HttpSession object.

ServletContext attributes

The ServletContext attributes are shared between requests and sessions. In order to access ServletContext attributes in Thymeleaf you can use theapplication. prefix:

        <table>
            <tr>
                <td>My context attribute</td>
                <!-- Retrieves the ServletContext attribute 'myContextAttribute' -->
                <td th:text="${application.myContextAttribute}">42</td>
            </tr>
            <tr>
                <td>Number of attributes</td>
                <!-- Returns the number of attributes -->
                <td th:text="${application.size()}">42</td>
            </tr>
            <tr th:each="attr : ${application.keySet()}">
                <td th:text="${attr}">javax.servlet.context.tempdir</td>
                <td th:text="${application.get(attr)}">/tmp</td>
            </tr>
        </table>

Spring beans

Thymeleaf allows accessing beans registered at the Spring Application Context with the @beanName syntax, for example:

    <div th:text="${@urlService.getApplicationUrl()}">...</div> 

In the above example, @urlService refers to a Spring Bean registered at your context, e.g.

    @Configuration
    public class MyConfiguration {
        @Bean(name = "urlService")
        public UrlService urlService() {
            return new FixedUrlService("somedomain.com/myapp); // some implementation
        }
    }
    
    public interface UrlService {
        String getApplicationUrl();
    }

This is fairly easy and useful in some scenarios.

 

 

 

转自:http://www.thymeleaf.org/doc/springmvcaccessdata.html

分享到:
评论

相关推荐

    spring mvc整合thymeleaf示例

    thymeleaf,我个人认为是个比较好的模板,性能也比一般的,比如freemaker的要高,而且把将美工和程序员能够结合起来,美工能够在浏览器中查看静态效果,程序员可以在应用服务器查看带数据的效果。 thymeleaf是一个...

    基于spring mvc+spring data+Thymeleaf+mysql的简单工程

    这是一个基于Spring MVC、Spring Data、Thymeleaf和MySQL数据库构建的简单Web应用程序工程。这个项目的核心在于利用这些技术栈来实现数据的CRUD(创建、读取、更新和删除)操作,并通过Web界面进行交互。 **Spring ...

    Java_学习如何使用Spring MVC和Thymeleaf创建Web页面.zip

    model.addAttribute("message", "Hello, Spring MVC and Thymeleaf!"); return "hello"; } } ``` 这里的`hello`方法将处理所有`/hello`路径的GET请求,将消息添加到Model中,然后返回视图名称。Thymeleaf会寻找...

    spring boot+hibernate+spring mvc+thymeleaf 实例

    spring boot+hibernate+spring mvc+thymeleaf 实例,下载导入即可运行,可独立部署到独立tomcat,可内置tomcat运行,配置都在,数据库mysql直接导入脚本即可,可加我扣扣410987712一起学习

    Spring mvc spring security Thymeleaf and Bootstrap

    Spring MVC、Spring Security、Thymeleaf 和 Bootstrap 是构建现代Web应用程序的重要技术栈。下面将分别详细介绍这些技术及其在后台管理中的应用。 1. Spring MVC: Spring MVC是Spring框架的一个模块,专门用于...

    thymeleaf-3.0.12.RELEASE-API文档-中文版.zip

    Maven坐标:org.thymeleaf:thymeleaf:3.0.12.RELEASE; 标签:thymeleaf、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码...

    thymeleaf-spring5-3.0.14.RELEASE-API文档-中英对照版.zip

    Maven坐标:org.thymeleaf:thymeleaf-spring5:3.0.14.RELEASE; 标签:thymeleaf、spring5、jar包、java、中英对照文档; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性...

    springmvc-thymeleaf-jpa:Spring MVC + Thymeleaf,Spring Security,Spring ORM + Spring Data JPA产品

    springmvc-百里香叶-jpa Spring MVC + Thymeleaf,Spring Security,Spring ORM + Spring Data JPA产品用以下技术开发的对象: Spring Security,Spring MVC和Thymeleaf。 Spring JDBC,Spring ORM,Spring Data JPA...

    spring boot+spring mvc+mybatis+thymeleaf整合开发学生成绩信息管理系统

    项目描述 学生成绩管理系统,有三...spring boot+spring mvc+mybatis+layui+jquery+thymeleaf http://localhost:8080/Sys/loginView 管理员账号 admin admin 老师登录 2020031920 111111 学生账号登录 20200319 111111

    spring-boot-gradle-mvc-thymeleaf:带有Thymeleaf的SpringBoot Gradle MVC示例应用程序

    标题中的“spring-boot-gradle-mvc-thymeleaf”是一个项目名称,表明这是一个使用Spring Boot、Gradle构建工具,并且结合了Model-View-Controller(MVC)架构和Thymeleaf模板引擎的示例应用。这个项目旨在帮助开发者...

    Spring.MVC-A.Tutorial-Spring.MVC学习指南 高清可复制版PDF

    在实际开发中,Spring MVC常常与Spring Data JPA或MyBatis等持久层框架结合使用,以方便数据库操作。此外,Spring MVC还能够与其他Spring模块(如Spring Security、Spring WebSocket等)无缝集成,提供完整的解决...

    spring boot+thymeleaf项目实战

    在本项目实战中,我们将深入探讨Spring Boot与Thymeleaf的集成应用,这是一个流行的Java Web开发框架组合,用于快速构建高效、现代化的Web应用程序。Spring Boot简化了Spring的配置,而Thymeleaf则是一个功能强大的...

    Spring+thymeleaf小示例

    标题“Spring+Thymeleaf小示例”指的是一个关于如何在Java web开发中整合Spring框架与Thymeleaf模板引擎的教程或项目实例。在这个示例中,开发者可能将学习如何利用这两者来创建动态网页应用。Thymeleaf是一种现代的...

    thymeleaf-3.0.5.zip

    thymeleaf-3.0.5中文文档,清晰无广告,官方中文翻译 1.Thymeleaf简介 2.示例项⽬:Good Thymes Virtual Grocery 3.使⽤⽂本 4.标准表达式语法 5.设置属性值 6.循环迭代 7.条件判断 8.模板布局 9.局部变量 10.属性...

    SpringThymeleafExample:关于 spring mvc、thymeleaf、maven 的示例。 Spring MVC Thymeleaf 集成

    在本示例中,`mvn tomcat:run`命令是使用Maven插件启动一个内嵌的Tomcat服务器,这样我们就可以直接在本地运行和测试Spring MVC与Thymeleaf集成的应用。 在"SpringThymeleafExample-master"这个压缩包中,我们可以...

    Spring3+ThymeLeaf

    标题 "Spring3+ThymeLeaf" 指的是在Spring框架的第三个主要版本(Spring 3)中结合Thymeleaf模板引擎来处理视图层的项目开发。Thymeleaf是一个现代、类型安全的模板引擎,常用于构建Web应用程序的前端。在描述中提到...

    SpringBoot+SpringSecurity+thymeleaf基础代码

    Spring Boot的核心理念是“约定优于配置”,它集成了大量的常用库,如Spring MVC、Data JPA等,使得开发者可以快速构建可运行的独立应用。在"SpringBoot+SpringSecurity+thymeleaf基础代码"项目中,我们可以看到这三...

    spring-boot-starter-thymeleaf-2.1.0.RELEASE.jar

    java运行依赖jar包

    springboot+mvc(thymeleaf)+静态模拟数据库(缺乏增删改).zip

    这个项目作为一个基础教程,可以帮助初学者了解如何将 Spring Boot、Spring MVC 和 Thymeleaf 结合起来构建 Web 应用。然而,对于实际生产环境,通常需要一个真正的数据库来存储和管理数据,并实现完整的 CRUD 功能...

Global site tag (gtag.js) - Google Analytics