使用thymeleaf如何在html中添加调用controller的功能,例如login页面点击登录后,进入index页面,Controller层使用RequestMapping
时间: 2024-05-02 15:18:30 浏览: 8
1. 首先,在Controller层中添加一个RequestMapping方法来处理登录请求,例如:
```
@RequestMapping(value="/login", method=RequestMethod.POST)
public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model) {
// 处理登录逻辑
if (isValidUser(username, password)) {
model.addAttribute("username", username);
return "index";
} else {
model.addAttribute("errorMessage", "Invalid username or password");
return "login";
}
}
```
2. 在login.html页面中,使用Thymeleaf的表单提交功能来调用Controller的登录方法,例如:
```
<form action="#" th:action="@{/login}" method="post">
<input type="text" name="username" placeholder="Username" required />
<input type="password" name="password" placeholder="Password" required />
<input type="submit" value="Login" />
</form>
```
3. 在Controller中的登录方法中,如果登录成功,将用户名添加到Model中,然后返回index.html页面。在index.html页面中,使用Thymeleaf表达式来显示用户名,例如:
```
<h1>Welcome, <span th:text="${username}"></span>!</h1>
```
这样,用户在登录页面输入用户名和密码后,点击登录按钮,将会调用Controller的登录方法,处理登录逻辑,然后根据返回值跳转到对应的页面。在index页面中,Thymeleaf表达式将会显示用户名。