thymeleaf onclick 重定向
时间: 2023-09-04 07:16:09 浏览: 45
可以使用Thymeleaf的内置属性th:href来实现onclick重定向。具体步骤如下:
1. 在HTML标签中添加th:href属性,指定重定向的地址。
2. 在onclick事件中使用location.href属性来实现重定向。
例如,下面的代码实现了点击按钮后重定向到指定页面的功能:
```html
<button onclick="location.href='@{/redirectUrl}'">重定向</button>
```
其中,@{/redirectUrl}是Thymeleaf的URL表达式,用于获取重定向地址。
相关问题
thymeleaf获取 重定向返回list集合
Thymeleaf是一个Java模板引擎,它主要用于Web应用程序中的动态HTML页面的渲染。
Thymeleaf不能直接从重定向中获取列表集合,因为重定向是在服务器端完成的,而Thymeleaf是在客户端完成的。但是,您可以使用ModelAndView对象将列表集合传递给重定向的目标页面。
以下是一个示例:
```java
@GetMapping("/redirect")
public ModelAndView redirectWithList() {
List<String> myList = Arrays.asList("item1", "item2", "item3");
ModelAndView modelAndView = new ModelAndView("redirect:/listPage");
modelAndView.addObject("myList", myList);
return modelAndView;
}
@GetMapping("/listPage")
public String displayListPage(Model model) {
List<String> myList = (List<String>) model.asMap().get("myList");
// Use the myList to display the list page
return "listPage";
}
```
在上面的示例中,`redirectWithList`方法将列表集合传递给`ModelAndView`对象,并将其设置为重定向的目标页面。然后,`listPage`方法从`Model`对象中获取列表集合并将其用于显示列表页面。
在Thymeleaf模板中,您可以使用Thymeleaf表达式来访问列表集合,例如:
```html
<ul>
<li th:each="item : ${myList}" th:text="${item}"></li>
</ul>
```
上面的代码将在页面上显示一个无序列表,其中每个列表项都是列表集合中的一个元素。
thymeleaf 重定向
在 Thymeleaf 中,重定向可以通过使用 Spring MVC 的 `RedirectView` 类来实现。你可以在控制器中使用 `RedirectView`,然后将其返回给 Thymeleaf 视图。例如:
```java
@GetMapping("/redirect")
public RedirectView redirectWithUsingRedirectView(RedirectAttributes attributes) {
attributes.addFlashAttribute("message", "Redirected with using RedirectView");
return new RedirectView("/hello");
}
```
在上面的示例中,我们使用 `RedirectView` 将请求重定向到 `/hello` 路径,并在重定向时添加了一条消息。
然后,在 Thymeleaf 视图中,你可以重定向到这个路径,如下所示:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Redirecting with Thymeleaf</title>
</head>
<body>
<h1>Redirecting with Thymeleaf</h1>
<div th:if="${message}">
<p th:text="${message}"></p>
</div>
<a th:href="@{/redirect}">Click here to redirect</a>
</body>
</html>
```
在上面的示例中,我们使用 Thymeleaf 的 `@{/redirect}` 表达式创建一个链接,并在单击该链接时将请求重定向到 `/redirect` 路径。