有人可以帮助我吗?我有 Spring Boot-thymeleaf 问题

问题描述 投票:0回答:1

我想从“登录管理”重定向到“管理仪表板”。但我无法重定向管理仪表板。我检查了所有数据库、配置 mvc 等,但我还没有找到问题出在哪里。我还问了 chatgpt 1000 次。

这是百里香代码

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Admin Login</title>
</head>
<body>
<h2>Admin Login</h2>
<form th:action="@{/login-admin}" method="post">
  <label for="username">Username:</label>
  <input type="text" id="username" name="username" required><br><br>

  <label for="password">Password:</label>
  <input type="password" id="password" name="password" required><br><br>

  <button type="submit">Login</button>
</form>

<div th:if="${param.error}" style="color: red;">
  <p>Invalid username or password. Please try again.</p>
</div>

</body>
</html>

这是控制器。

   @PostMapping("/login-admin")
    public String loginAdmin(@RequestParam("username") String username,
                             @RequestParam("password") String password,
                             Model model) {
        if (username.isEmpty() || password.isEmpty()) {
            model.addAttribute("error", "username and password cannot empty.");
            return "login-admin"; // Error handling for empty inputs
        }
        
        Admin admin = adminRepository.findByUsername(username);
        if (admin == null || !passwordEncoder.matches(password, admin.getPassword())) {
            model.addAttribute("error", "password or username wrong.");
            return "login-admin"; // Incorrect login
        }

        // Successful login
        return "redirect:/admin-dashboard"; // Redirect to admin dashboard
    }

你能解决这个问题吗

java html spring spring-boot thymeleaf
1个回答
0
投票

通过返回纯字符串进行重定向仅适用于

@Controller
带注释的方法。对于那些用
@RestController
注释的,您可以使用
RedirectView

@PostMapping("/login-admin")
public ModelAndView loginAdmin(..., Model model)
{
   if (condition1) {
      model.addAttribute(...);
      return new ModelAndView("login-admin", model);
   } else {
       return new ModelAndView(new RedirectView("/login-admin"));
   )
}
© www.soinside.com 2019 - 2024. All rights reserved.