1. 创建对象-----user
package com.cc.springboot.entity;
public class User {
private String username;
// 1:女 2:男
private Integer gender;
public User() {
}
public User(String username, Integer gender) {
this.username = username;
this.gender = gender;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
}
2.controller
package com.cc.springboot.controller;
import com.cc.springboot.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Controller
public class HelloController {
@ResponseBody
@RequestMapping("/success")
public String hello(){
return "hello cc";
}
@RequestMapping("/study")
public String study(Map<String, Object> map, HttpServletRequest request){
List<User> userList=new ArrayList<>();
userList.add(new User("小梦",1));
userList.add(new User("小里",2));
userList.add(new User("小岚",1));
map.put("userList",userList);
map.put("desc","欢迎来到<h1>cc</h1>");
request.getSession().setAttribute("user",new User("小刘",2));
return "study";
}
}
3.模板实现
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${desc}"></div>
<!--不转义特数字符,直接显示应有的效果-->
<div th:utext="${desc}"></div>
<br/>
<!--th:object 获取到session对象-->
<div th:object="${session.user}">
<!--上面已经将对象获取出来了,下面直接写属性名就可以-->
<p>姓名:<span th:text="*{username}"></span></p>
<p>性别:<span th:text="*{gender == 1? '女':'男'}"></span></p>
</div>
</body>
</html>
关键-》(th:text th:utext) (th:object ) *{} 存入的session对象