thymeleaf前端如何转跳到controller层
时间: 2023-10-27 09:16:49 浏览: 32
在Thymeleaf中,可以使用表单(form)标签将用户输入的数据提交到后端的Controller中,从而实现页面的转跳。以下是一个示例:
1. 在Thymeleaf的HTML页面中,使用表单(form)标签,设置表单的提交路径和提交方式(POST或GET):
```
<form action="/submitForm" method="post">
<!--表单内容-->
</form>
```
2. 在Controller中,编写一个处理表单提交的方法(方法名可以任意取),用于接收表单提交的数据,并进行相应的处理:
```
@PostMapping("/submitForm")
public String submitForm(@RequestParam("param1") String param1, @RequestParam("param2") String param2) {
//处理表单提交的数据
return "redirect:/successPage";
}
```
在上面的代码中,@PostMapping注解表示该方法处理POST请求,路径为"/submitForm"。@RequestParam注解表示该方法接收的请求参数,param1和param2分别为表单中输入框的name属性值。
3. 在Controller中,再编写一个显示处理结果的方法(方法名可以任意取),用于将处理结果显示在页面上:
```
@GetMapping("/successPage")
public String successPage(Model model) {
//向模型中添加数据,用于在页面上显示
model.addAttribute("result", "处理成功");
return "successPage";
}
```
在上面的代码中,@GetMapping注解表示该方法处理GET请求,路径为"/successPage"。Model参数用于向模型中添加数据,"result"为Key,"处理成功"为Value。
4. 在Thymeleaf的HTML页面中,通过Thymeleaf的语法,将Controller中添加到模型中的数据显示在页面上:
```
<h1 th:text="${result}"></h1>
```
以上就是在Thymeleaf中实现页面转跳到Controller的简单示例。