thymeleaf的简单用法
一般用到的是
@{} | 使用链接的时候使用该表达式 |
${} | 使用请求域、session域,对象等值 |
三个不常用的。
*{}、#{}、~{}。
如果变量没有在标记内,需要用到行内用法。需要在表达式的两边加上两个中括号包围。
模拟登录
准备
新建项目的时候需要勾选的资源:
将需要使用的静态资源放到static文件夹下面:
将需要使用的页面放到templates文件夹下面:
登录部分的代码
为了登录,我们需要新建一个User类。
使用了lombok@Data减少代码。
@Data
public class User {
public String userName;
public String password;
}
接下来需要在html网页的代码中添加一些thymeleaf的代码:
如果要使用thymeleaf,需要在html标签内添加下面的声明:
<html lang="en" xmlns="http://www.thymeleaf.org">
将表单的action进行thymeleaf的修改:
1、修改表单的请求方式与链接:
<form class="form-signin" action="index.html" method="post" th:action="@{/index}">
方法使用post。使用th:action和@{}方法将action修改为/index链接。下面的java代码中写了/向index链接发出post请求的处理逻辑。
2、修改给输入框添加name属性,添加提示框。
<label style="color: red" th:text="${msg}"></label>
<input type="text" name="userName" class="form-control" placeholder="用户名" autofocus>
<input type="password" name="password" class="form-control" placeholder="密码">
input标签的两个name需要和User类的两个属性的变量名相对应起来。并且给提示框使用thymeleaf传入一个msg,下面的代码展示了如何使用model添加msg。
@Controller
public class IndexController {
// 登录页的访问
@GetMapping(value = {"/", "login"})
public String LoginPage(){
return "Login";
}
// 提交表单后后进入index页面的函数
// 账号的验证只是用了非空的判断
// 使用重定向的方法,防止网页重复提交表单
@PostMapping(value = "/index")
public String Main(User user, HttpSession session, Model model){
if(StringUtils.hasLength(user.getUserName()) && StringUtils.hasLength(user.getPassword())){
session.setAttribute("loginUser",user);
return "redirect:index.html";
}else{
model.addAttribute("msg","账号密码错误!");
return "login";
}
}
// 重定向或刷新网页 index
@GetMapping("/index.html")
public String MainPage(HttpSession session, Model model){
if(session.getAttribute("loginUser")!=null){
return "index";
}else{
model.addAttribute("msg","请重新登录!");
return "login";
}
}
}
如果账号密码为空就会显示账号密码错误:
如果直接访问index页面,就会显示请重新登录:
3、将登录的名字修改为用户名。
在index.html页面找到放名字的地方,使用行内写法,将Session中User的userName传给这个地方。
<a href="#" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<img src="images/photos/user-avatar.png" alt="" />
[[${session.loginUser.userName}]]
<span class="caret"></span>
</a>
这样登录后的名字就为用户名了。