• SpringMvc学习之旅与Thymeleaf的常用用法


     哈喽~大家好呀,这篇继续上篇的SpringMvc讲解与Thymeleaf的常用用法。

     🥇个人主页:个人主页​​​​​             

    🥈 系列专栏:【Java框架】   

    🥉与这篇相关的文章:            

    目录

    一、前言

    1、ModelAndView 详解

    二、Servlet重定向forward与redirect

    1、Model

    三、thymeleaf 的用法

    1、Thymeleaf 的特点

    2、常用的语法

    3、th属性


    一、前言

    1、ModelAndView 详解

    前面写到,当控制器处理完请求时,通常会将包含视图名称或视图对象以及一些模型属性的ModelAndView对象返回到DispatcherServlet。

    ModelAndView 当中包含了一个model属性和一个view属性,model其实是一个 ModelMap 类型,它是一个LinkedHashMap的子类,view包含了一些视图信息。

    如何使用?

    ModelAndView 通过 setViewName方法来实现跳转的页面。

    eg:跳转的页面 mv.setViewName("user/userInfo"); 就是跳转到 user的userInfo页面

    addObject

    addObject 该方法用于设置【前端页面要显示的数据是什么】;该方法的参数:可以是任何一个有效的Java对象;该方法默认把对象,存放在当前请求中的;

    通过设置键值对的方式来实现传给页面的值。

    eg:

    1. <body class="login_bg">
    2.    <section class="loginBox">
    3.        <header class="loginHeader">
    4.            <h1>超市订单管理系统h1>
    5.        header>
    6.        <section class="loginCont">
    7.        <form class="loginForm" action="${pageContext.request.contextPath }/user/login"  name="actionForm" id="actionForm"  method="post" >
    8. <div class="info">${error }div>
    9. <div class="inputbox">
    10.                    <label for="user">用户名:label>
    11. <input type="text" class="input-text" id="userCode" name="usercode" placeholder="请输入用户名" required/>
    12. div>
    13. <div class="inputbox">
    14.                    <label for="mima">密码:label>
    15.                    <input type="password" id="userPassword" name="userpassword" placeholder="请输入密码" required/>
    16.                div>
    17. <div class="subBtn">
    18.                    <input type="submit" value="登录"/>
    19.                    <input type="reset" value="重置"/>
    20.                div>
    21. form>
    22.        section>
    23.    section>
    24. body>

    该页面是超市管理系统的登录页面,看 input 里面的name属性,用户名的name属性是usercode,那么addObject传值是 mv.addObject(“usercode”,xxx)来传值,注:记得大小写一定要对上

    二、Servlet重定向forward与redirect

    使用servlet重定向有两种方式,一种是forward,另一种就是redirect。forward是服务器内部重定向,客户端并不知道服务器把你当前请求重定向到哪里去了,地址栏的url与你之前访问的url保持不变。redirect则是客户端重定向,是服务器将你当前请求返回,然后给个状态标示给你,告诉你应该去重新请求另外一个url,具体表现就是地址栏的url变成了新的url。

    eg:

    1. ModelAndView mv = new ModelAndView("/user/save/result");//默认为forward模式  
    2. ModelAndView mv = new ModelAndView("redirect:/user/save/result");//redirect模式  

    1、Model

    Model 作用: 作为数据流转的载体,相当于前端的一个数据库,就好比后端中的user实体类所对应的数据库User, 从Model中获取数据比从后端的User实体类中获取数据更加方便。

    img

    如图,这是一个简单的实例,简单展示一下Model是怎么存储数据然后展示到前段页面的。

    控制层

    1. @Controller
    2. // 在Spring MVC 中使用 @RequestMapping 来映射请求,也就是通过它来指定控制器可以处理哪些URL请求,相当于Servlet中在web.xml中配置
    3. @RequestMapping("/user")
    4. public class UserAction {
    5.    @RequestMapping("/test04")
    6.    public String test02(Model model){
    7.        User user = new User("Lucy","123456",18);
    8.        // return "userInfo";
    9.        System.out.println(user);
    10.        model.addAttribute("user",user);
    11.        return "userDetail";
    12.   }
    13. }

    前台页面

    1. <html>
    2. <head>
    3.    <title>Titletitle>
    4. head>
    5. <body>
    6.    <h1>用户详情页h1>
    7.    <h1>姓名:${user.username}h1>
    8.    <h1>密码:${user.password}h1>
    9.    <h1>年龄:${user.age}h1>
    10. body>
    11. html>

    访问地址

    http://localhost:8080/day09_SpringMvc01/user/test04

    效果

    如果使用 HttpServletRequest 或 HttpSession 来传数据呢?

    1.    @RequestMapping("/test05")
    2.    public String test03(User user, Model model, HttpServletRequest request, HttpSession session){
    3.        user = new User("Lucy","123456",18);
    4.        // return "userInfo";
    5.        // user放入Session
    6.        // 用到ServletAPI
    7.        request.setAttribute("requestKey","requestValue");
    8.        session.setAttribute("sessionKey","sessionValue");
    9.        model.addAttribute("user",user);
    10.        return "userDetail";
    11.   }

    前台页面

    1. <html>
    2. <head>
    3.    <title>Titletitle>
    4. head>
    5. <body>
    6.    <h1>用户信息页面h1>
    7.   姓名:${user.name} <br>
    8.   年龄:${user.age} <br>
    9.   requestValue:${requestKey} <br>
    10.   sessionValue:${sessionKey} <br>
    11. body>
    12. html>

    springMVC.xml 配置说明

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3.       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4.       xmlns:context="http://www.springframework.org/schema/context"
    5.       xmlns:mvc="http://www.springframework.org/schema/mvc"
    6.       xsi:schemaLocation="http://www.springframework.org/schema/beans
    7. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    8. http://www.springframework.org/schema/context
    9. http://www.springframework.org/schema/context/spring-context-4.0.xsd
    10. http://www.springframework.org/schema/mvc
    11. http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    12. ">
    13.    <context:component-scan base-package="com.itxzw">
    14.        <context:exclude-filter type="regex" expression="com.itxzw.util"/>
    15.    context:component-scan>
    16.    
    17.    
    18.    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    19.        <property name="prefix" value="/WEB-INF/view/"/>
    20.        <property name="suffix" value=".jsp" />
    21.    bean>
    22.    
    23.    <mvc:annotation-driven />
    24. beans>
    25. web.xml 配置说明
    26. "1.0" encoding="UTF-8"?>
    27. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    28.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    29.         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    30.         version="4.0">
    31.  <servlet>
    32.    <servlet-name>dispatcherServletservlet-name>
    33.    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    34.    <init-param>
    35.      <param-name>contextConfigLocationparam-name>
    36.      <param-value>classpath:springMVC.xmlparam-value>
    37.    init-param>
    38.  servlet>
    39.  <servlet-mapping>
    40.    <servlet-name>dispatcherServletservlet-name>
    41.    <url-pattern>/url-pattern>
    42.  servlet-mapping>
    43. web-app>

    主要理解 DispatcherServlet 的流程理解,控制层传前台可以理解为使用了类似于键值对的方式进行获取值的。

    三、thymeleaf 的用法

    Thymeleaf 是新一代 Java 模板引擎,与 Velocity、FreeMarker 等传统 Java 模板引擎不同,Thymeleaf 支持 HTML 原型,其文件后缀为“.html”,因此它可以直接被浏览器打开,此时浏览器会忽略未定义的 Thymeleaf 标签属性,展示 thymeleaf 模板的静态页面效果;当通过 Web 应用程序访问时,Thymeleaf 会动态地替换掉静态内容,使页面动态显示。

    使用它,需要在 html 标签中,增加额外属性来达到 “模板+数据” 的展示方式,示例代码如下。

    1. html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4.    <meta charset="UTF-8">
    5.    <title>Titletitle>
    6. head>
    7. <body>
    8. <h1 th:text="迎您来到Thymeleaf">欢迎您访问静态页面 HTMLh1>
    9. body>
    10. html>

    效果

    1、Thymeleaf 的特点

    Thymeleaf 模板引擎具有以下特点:

    动静结合:Thymeleaf 既可以直接使用浏览器打开,查看页面的静态效果,也可以通过 Web 应用程序进行访问,查看动态页面效果。

    开箱即用:Thymeleaf 提供了 Spring 标准方言以及一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

    多方言支持:它提供了 Thymeleaf 标准和 Spring 标准两种方言,可以直接套用模板实现 JSTL、 OGNL 表达式;必要时,开发人员也可以扩展和创建自定义的方言。

    与 SpringBoot 完美整合:SpringBoot 为 Thymeleaf 提供了的默认配置,并且还为 Thymeleaf 设置了视图解析器,因此 Thymeleaf 可以与 Spring Boot 完美整合。

    注:要使用 Thymeleaf 就要在 html 导入额外属性

    xmlns:th="http://www.thymeleaf.org"

    2、常用的语法

    表达式

    变量表达式:${...}

    选择变量表达式:*{...}

    链接表达式:@{...}

    国际化表达式:#{...}

    片段引用表达式:~{...}

    本人常用的是变量表达式

    假设获取 person 对象的 name属性,表达式形式如下:

    ${person.name}

    3、th属性

    属性描述示例
    th:id替换 HTML 的 id 属性
    th:text文本替换,转义特殊字符

    hello

    th:utext文本替换,不转义特殊字符
    欢迎你
    th:object在父标签选择对象,子标签使用 *{…} 选择表达式选取值。 没有选择对象,那子标签使用选择表达式和 ${…} 变量表达式是一样的效果。 同时即使选择了对象,子标签仍然可以使用变量表达式。

    firstname

    th:value替换 value 属性
    th:with局部变量赋值运算
    th:style设置样式
    编程帮 www.biancheng.net
    th:onclick点击事件
    th:each遍历,支持 Iterable、Map、数组等。
    th:if根据条件判断是否需要展示此标签
    th:unless和 th:if 判断相反,满足条件时不显示
    th:switch与 Java 的 switch case语句类似 通常与 th:case 配合使用,根据不同的条件展示不同的内容
    编程帮 www.biancheng.net
    th:fragment模板布局,类似 JSP 的 tag,用来定义一段被引用或包含的模板片段
    插入的内容
    th:insert布局标签; 将使用 th:fragment 属性指定的模板片段(包含标签)插入到当前标签中。
    th:replace布局标签; 使用 th:fragment 属性指定的模板片段(包含标签)替换当前整个标签。
    th:selectedselect 选择框选中
    th:src替换 HTML 中的 src 属性
    th:inline内联属性; 该属性有 text、none、javascript 三种取值, 在
    th:action替换表单提交地址

    不积跬步无以至千里,趁年轻,使劲拼,给未来的自己一个交代!向着明天更好的自己前进吧!

  • 相关阅读:
    SRS 功能介绍及Log分析
    C/C++ 11/14/17 有栈式协同程式的基础框架类库【关于】
    [题] 年会抽奖 #错排问题 #递推
    24.98万起,新一代AITO问界M7值得买吗?
    淘宝退货退款测试用例
    [学习记录] 设计模式 3. 观察者模式
    设计模式之创建型模式:工厂模式
    SSM框架学习(三、MyBatis实践:提高持久层数据处理效率)
    《深度学习500问》外链笔记
    数据库以及数据库常用概念、ER模型相关概念
  • 原文地址:https://blog.csdn.net/aasd23/article/details/127457126