1. 程式人生 > 其它 >html解析Model與ModelandView測試

html解析Model與ModelandView測試

技術標籤:SSMmvcspring

解析

關於html解析這個的話我使用的是thymeleaf解析模板,這裡貼上ssm引入thymeleaf的程式碼

Maven匯入

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

檢視解析器:

注意,有這個解析器以後將jsp的解析器註釋掉

    <bean id="templateResolver"
          class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".html"/>
        <property name="templateMode" value="HTML5"/>
    </bean>
    <bean id="templateEngine"
          class="org.thymeleaf.spring5.SpringTemplateEngine">
        <property name="templateResolver" ref="templateResolver"/>
    </bean>

    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="templateEngine" ref="templateEngine"/>
        <property name="characterEncoding" value="UTF-8"/>
    </bean>

測試Demo

後端

@Controller
public class HelloController {
    @RequestMapping(path = "/hello.do")
    public String sayHello(Model model){
        System.out.println("hello springmvc");
        model.addAttribute("hello","pyx");
        return "success";
    }
}

前端

<!DOCTYPE html>
<html lang="zh-CN"
    xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="JS/model.js" type="text/javascript"></script>
    <script src="JS/jquery-3.5.1.js" type="text/javascript"></script>
</head>
<body>
<div th:text="${hello}">你好
</div>
</body>
</html>

顯示

在這裡插入圖片描述

正題

強推大佬文章
一下全是從該文章我瞭解的總結

Model與ModelMap

Model與ModelMap:就是一個模型,他在前端向後端請求時自動建立。
對於這個模型我們可以通過addAttribute()設定屬性。

ModelandView

他有一個模型與檢視,所以我們可以對其設定檢視,也可以在其裡面新增屬性,在稍後的檢視解析器裡面,對其自動解析後返回新檢視。