SpringBoot入门(五)Thymeleaf语法之日期转换、条件判断、获取作用域对象值

前言

      本章继续来谈Thymeleaf语法中较为关键的三种:日期转换、条件判断、获取作用域对象值

方法

本章示例沿用上一章节的示例内容

修改controller:

package cn.edu.ccut.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {

	@RequestMapping("/showMsg")
	public String getMsg(HttpServletRequest request, Model model){
		model.addAttribute("msg", "this is thymeleaf !");
		model.addAttribute("time", new Date());
		model.addAttribute("sex", "男");
		model.addAttribute("num", 2);
		request.setAttribute("req", "request");
		request.getSession().setAttribute("ses", "session");
		request.getSession().getServletContext().setAttribute("app", "application");
		return "index";
	}
}

1.日期转换

日期转换包含格式化时间,还有获取具体的年、月、日

<!DOCTYPE html>
<html>
<head>
	<title>Thymeleaf</title>
</head>
<body>
	<!-- 格式化时间 -->
	<span th:text="${#dates.format(time)}"></span><br/>
	<span th:text="${#dates.format(time,'yyyy-MM-dd')}"></span><br/>
	<!-- 获取年月日 -->
	<span th:text="${#dates.year(time)}"></span><br/>
	<span th:text="${#dates.month(time)}"></span><br/>
	<span th:text="${#dates.day(time)}"></span>
</body>
</html>

执行结果如下:

2.条件判断

1)比较运算符

gt:great than(大于)>
ge:great equal(大于等于)>=
eq:equal(等于)==
lt:less than(小于)<
le:less equal(小于等于)<=
ne:not equal(不等于)!=

使用示例:

<!DOCTYPE html>
<html>
<head>
	<title>Thymeleaf</title>
</head>
<body>
	<span th:if="${sex} == '男' ">
		性别:男
	</span>
	<span th:if="${sex} == '女' ">
		性别:女
	</span>
	<span th:if="${sex} eq '男' ">
		性别:男
	</span>
	<span th:if="${sex} eq '女' ">
		性别:女
	</span>
</body>
</html>

2)其他运算符

switch...case...

<!DOCTYPE html>
<html>
<head>
	<title>Thymeleaf</title>
</head>
<body>
	<div th:switch="${num}">
	  <p th:case="1">数字是1</p>
	  <p th:case="2">数字是2</p>
	</div>
</body>
</html>

3.获取作用域对象值

我们学习JSP的时候获取过三大作用域对象的值,即request、session、application

那么thymeleaf也是可以获取的,语法如下所示:

<!DOCTYPE html>
<html>
<head>
	<title>Thymeleaf</title>
</head>
<body>
	request:<span th:text="${req}"/><br/>
	session:<span th:text="${session.ses}"/><br/>
	application:<span th:text="${application.app}"/>
</body>
</html>

 

这里仍然要明确的是:${data}与${param.data}的区别?


前者相当于从后台获取的值,即request.getAttribute("data");的值

后者相当于从页面传递过来的值,即request.getParameter("data");的值

这一点,我相信大家学习JSP的时候应该已经注意到了这个问题,我这里多啰嗦一下!

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值