springmvc整合thymeleaf

这篇具有很好参考价值的文章主要介绍了springmvc整合thymeleaf。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

概述

Thymeleaf提供了一组Spring集成,使您可以将其用作Spring MVC应用程序中JSP的全功能替代品。

这些集成将使您能够:

  • @Controller像使用JSP一样,将Spring MVC 对象中的映射方法转发到Thymeleaf管理的模板。
  • 在模板中使用Spring表达式语言(Spring EL)代替OGNL。
  • 在与表单支持Bean和结果绑定完全集成的模板中创建表单,包括使用属性编辑器,转换服务和验证错误处理。
  • 显示Spring管理的消息文件中的国际化消息(通过常规MessageSource对象)。
  • 使用Spring自己的资源解析机制解析您的模板。

thymeleaf自己也做了spring的集成,所以我们并不需要做太多的配置,就可以达到我们想要的结果。thymeleaf提供了两种集成方法:①、注解配置,也就是java代码,②、xml文件配配置,本文主要介绍第二种xml配置。

你能get到的知识点:

1、springmvc整合thymeleaf

2、spring提供的三种model的使用

3、解决html前端thymeleaf不生效问题(见问题1)

4、解决html前端显示乱码问题(见问题2)

springmvc整合thymeleaf

springmvc整合thymeleaf

一:加入依赖

在springmvc里面,除了要加入 thymeleaf的主依赖之外,还需要 thymeleaf-spring4,否则会报 org.thymeleaf.spring4.view.ThymeleafViewResolver,找不到thymeleaf解析器,所以 thymeleaf-spring4也是必不可少的。

Thymeleaf具有针对Spring Framework 3.x和4.x的集成,由两个独立的库分别称为thymeleaf-spring3和提供thymeleaf-spring4。这些库打包在单独的.jar文件(thymeleaf-spring3-{version}.jar和thymeleaf-spring4-{version}.jar)中,需要添加到类路径中,以便在应用程序中使用Thymeleaf的Spring集成

            <!--        thymeleaf-->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring4</artifactId>
            <version>3.0.11.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.11.RELEASE</version>
        </dependency>

复制

在springmvc配置文件中配置thymeleaf解析器,官方文档中Thymeleaf提供了上述两个接口的实现:

    org.thymeleaf.spring4.view.ThymeleafView
    org.thymeleaf.spring4.view.ThymeleafViewResolver

复制

不过现在都已经被 org.thymeleaf.spring4.view.ThymeleafViewResolver所代替,至于以上配置是否还能够生效,就要靠你来试试了。

 <!-- thymeleaf 模板解析器 -->
    <bean id="templateResolver" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".html" />
        <property name="templateMode" value="HTML" />
        <property name="cacheable" value="false" />
        <property name="characterEncoding" value="UTF-8"/>
    </bean>

    <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
        <property name="templateResolver" ref="templateResolver" />
    </bean>

    <!--    视图解析器-->
    <bean id="viewResolver" class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
        <property name="templateEngine" ref="templateEngine" />
        <property name="characterEncoding" value="UTF-8"/>
    </bean>

复制

ViewResolvers是负责获取特定操作和语言环境的View对象的对象。通常,控制器要求ViewResolvers转发到具有特定名称的视图(由controller方法返回的String),然后应用程序中的所有视图解析器将按有序链执行,直到其中一个能够解析该视图为止。如果返回了View对象,并且将控件传递给该对象以呈现HTML。

注:值得注意的是,如果自己设置了spring的视图解析器,需要将其注释掉,否则thymeleaf解析器可能不会生效,我就是因为这个调试了好久,最后才发现这个问题。

<!--    配置视图解析器 prefix:前缀, suffix:后缀   使用thymeleaf需要将其注释掉-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".html"/>
    </bean>

复制

:编写控制器

需要从控制层传数据到视图时,我们就会使用model,常用的三种model就是:Model、ModelMap、ModelAndView。使用这三种model时,spring框架自动创建实例并作为controller的入参,用户无需自己创建

1、使用Model

/**
     * 在Model里存入一个用户信息
     * @return hello页面
     */
    @GetMapping("returnModelAndView")
    public String returnModelAndView(Model model){
        model.addAttribute("userInfo",new UserInfo("lomtom","123",new Address("湖南","邵阳")));
        return "hello";
    }

复制

Model是一个接口, Model源码:

public interface Model {
    Model addAttribute(String var1, Object var2);

    Model addAttribute(Object var1);

    Model addAllAttributes(Collection<?> var1);

    Model addAllAttributes(Map<String, ?> var1);

    Model mergeAttributes(Map<String, ?> var1);

    boolean containsAttribute(String var1);

    Map<String, Object> asMap();
}

复制

2、使用ModelMap

ModelMap继承LinkedHashMap

ModelMap源码:

public class ModelMap extends LinkedHashMap<String, Object> {
    public ModelMap() {
    }

    public ModelMap(String attributeName, Object attributeValue) {
        this.addAttribute(attributeName, attributeValue);
    }

    public ModelMap(Object attributeValue) {
        this.addAttribute(attributeValue);
    }

    public ModelMap addAttribute(String attributeName, Object attributeValue) {
        Assert.notNull(attributeName, "Model attribute name must not be null");
        this.put(attributeName, attributeValue);
        return this;
    }

    public ModelMap addAttribute(Object attributeValue) {
        Assert.notNull(attributeValue, "Model object must not be null");
        return attributeValue instanceof Collection && ((Collection)attributeValue).isEmpty() ? this : this.addAttribute(Conventions.getVariableName(attributeValue), attributeValue);
    }

    public ModelMap addAllAttributes(Collection<?> attributeValues) {
        if (attributeValues != null) {
            Iterator var2 = attributeValues.iterator();

            while(var2.hasNext()) {
                Object attributeValue = var2.next();
                this.addAttribute(attributeValue);
            }
        }

        return this;
    }

    public ModelMap addAllAttributes(Map<String, ?> attributes) {
        if (attributes != null) {
            this.putAll(attributes);
        }

        return this;
    }

    public ModelMap mergeAttributes(Map<String, ?> attributes) {
        if (attributes != null) {
            Iterator var2 = attributes.entrySet().iterator();

            while(var2.hasNext()) {
                Entry<String, ?> entry = (Entry)var2.next();
                String key = (String)entry.getKey();
                if (!this.containsKey(key)) {
                    this.put(key, entry.getValue());
                }
            }
        }

        return this;
    }

    public boolean containsAttribute(String attributeName) {
        return this.containsKey(attributeName);
    }
}

复制

3、使用ModelAndView

/**
     * 在ModelAndView里存入一个用户信息
     * @return ModelAndView
     */
    @GetMapping("returnModelAndView")
    public ModelAndView returnModelAndView(ModelAndView modelAndView){
        modelAndView.setViewName("hello");
        modelAndView.addObject("userInfo",new UserInfo("lomtom","123",new Address("湖南","邵阳")));
        return modelAndView;
    }

复制

ModelAndView顾名思义就是模型和试图的结合。ModelAndView源码:

public class ModelAndView {
    private Object view;
    private ModelMap model;
    private HttpStatus status;
    private boolean cleared = false;

    ......
}

复制

四:编写html

首先,写一个链接,请求 returnModelAndView请求。

<a href="returnModelAndView">ModelAndView</a>

复制

然后,写hello.html页面用于验证

<h2>你好啊,你成功了</h2>
<p th:text="${userInfo.userName}+'来自'+${userInfo.address.province}+${userInfo.address.city}"></p>

复制

五:结果

springmvc整合thymeleaf

六:记录我遇到的问题

问题1:配置好一切后,thymeleaf无法解析,所有关于thymeleaf的显示都无法生效。解决:由于我配置了spring的视图解析,所以导致thymeleaf的试图解析无法生效,所以去掉spring的视图解析。

thmelaf介绍Springmvc的视图解析:快速浏览其属性足以了解其配置方式:

  • viewClass建立View实例的类。对于JSP解析器,这是必需的,但是当我们与Thymeleaf合作时,根本不需要。
  • prefix与suffixThymeleaf的TemplateResolver对象中相同名称的属性的工作方式相似。
  • order 确定在链中查询ViewResolver的顺序。
  • viewNames 允许使用此ViewResolver解析视图名称(带通配符)。

问题2:前端显示乱码,具体表现为后台传入的不乱码,但是html中原本存在的乱码。解决:在试图解析器和模板解析器中加入参数:<propertyname="characterEncoding"value="UTF-8"/>文章来源地址https://www.toymoban.com/news/detail-484075.html

到了这里,关于springmvc整合thymeleaf的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringBoot 整合Thymeleaf教程及使用

    Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎。它与 JSP,Velocity,FreeMaker 等模板引擎类似,也可以轻易地与 Spring MVC 等 Web 框架集成。与其它模板引擎相比,Thymeleaf 最大的特点是,即使不启动 Web 应用,也可以直接在浏览器中打开并正确显示模板页面 。 目录 一、整合

    2024年02月06日
    浏览(28)
  • 前端模板引擎Thymeleaf的整合和使用

    目录 一、添加依赖 1.1首先,在项目的构建文件中(比如 Maven 或 Gradle)添加 Thymeleaf 的依赖。例如,对于 Maven 项目,在 pom.xml 文件中添加以下依赖 1.2保存并更新项目依赖 二、配置Thymeleaf 2.1模板位置配置 2.2模板缓存配置 2.3自定义标签配置 三、创建模板文件 3.1创建一个HTML文

    2024年04月27日
    浏览(42)
  • SpringBoot 整合Thymeleaf教程及使用 springboot配合thymeleaf,调用接口不跳转页面只显示文本

    Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎。它与 JSP,Velocity,FreeMaker 等模板引擎类似,也可以轻易地与 Spring MVC 等 Web 框架集成。与其它模板引擎相比,Thymeleaf 最大的特点是,即使不启动 Web 应用,也可以直接在浏览器中打开并正确显示模板页面 。 目录 一、整合

    2024年02月08日
    浏览(66)
  • 【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎

    🌕博客x主页:己不由心王道长🌕! 🌎文章说明:spring🌎 ✅系列专栏:spring 🌴本篇内容:对SpringBoot进行一个入门学习及对Thymeleaf模板引擎进行整合(对所需知识点进行选择阅读呀~)🌴 ☕️每日一语:在人生的道路上,即使一切都失去了,只要一息尚存,你就没有丝毫理

    2023年04月23日
    浏览(32)
  • idea利用spring框架整合thymeleaf展现数据库数据

    idea初步利用thymeleaf展现列表 上一篇文章简单展现自己写的列表; 这篇文章连接mysql数据库实现数据库数据展现 主要三个文件 controller指定html界面 mapper写数据库sql查询语句 pojo中的user写具体数据库中的表包含哪些字段(这部分最好的方式写出变量名字然后alt+insert自动生成g

    2024年02月05日
    浏览(45)
  • springboot整合security,mybatisPlus,thymeleaf实现登录认证及用户,菜单,角色权限管理

    本系统为springboot整合security,mybatisPlus,thymeleaf实现登录认证及用户,菜单,角色权限管理。页面为极简模式,没有任何渲染。 源码:https://gitee.com/qfp17393120407/spring-boot_thymeleaf 架构截图 此处以用户表为例,其他表数据可在源码获取。 用户表 共用属性 共用属性自动填充配置

    2024年02月07日
    浏览(39)
  • 【Spring Boot】Thymeleaf模板引擎 — Thymeleaf入门

    主要介绍什么是Thymeleaf以及Spring Boot如何集成使用Thymeleaf模板,最后介绍Spring Boot支持的Thymeleaf的一些常用的配置参数。 Thymeleaf是一款非常优秀的服务器端页面模板引擎,适用于Web和独立环境,具有丰富的标签语言和函数,能够处理HTML、XML、JavaScript甚至文本。 Thymeleaf相较于

    2024年02月05日
    浏览(33)
  • 【SpringBoot】| Thymeleaf 模板引擎

    目录 Thymeleaf 模板引擎 1. 第一个例子 2. 表达式 ①标准变量表达式 ②选择变量表达式(星号变量表达式) ③链接表达式(URL表达式) 3. Thymeleaf的属性 ①th:action ②th:method ③th:href ④th:src ⑤th:text ⑥th:style ⑦th:each (重点) ⑧条件判断 if-unless ⑨switch-case 判断语句 ⑩th:inline内联

    2024年02月08日
    浏览(27)
  • Thymeleaf模版引擎初尝试

    模版引擎虽然不能够实现代码与视图解耦,但是其适合于个人开发者使用,而且如果存在前后端项目中,前端大量请求后端时,模版引擎无疑也存在优势。 SpringBoot 整合步骤: 引入依赖 编写 yml 配置 编写 html 模版文件 编写 Controller 接口

    2024年02月13日
    浏览(32)
  • thymeleaf模板引擎

    ThymeleafProperties 配置类 1.默认编码 2.前缀 3.后缀 相当于视图解析器    这是学SpringBoot的必经之路,非常重要!!!(除非你是学前端的)   只改了前端代码点一下这个就可以刷新    传值过来了  th:text=\\\"${msg}\\\"爆红,但是可以显示,File-Settings-Editor-Inspection  取消“Expression

    2024年02月14日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包