-1

I am using Thymeleaf forms and traditional Spring rest controllers to make API requests to an external platform.

The Thymeleaf form is a simple login form with 2 fields and a submit button. After the user presses submit, the data from the 2 fields needs to be sent as request parameters to a GET mapping method inside the controller.

What's the easiest way to achieve this?

Thanks

  • Your question is duplicated. Please [see](https://stackoverflow.com/questions/43305607/request-parameter-with-thymeleaf) – Shahab Ranjbary Mar 31 '23 at 00:55
  • The answer to that question uses a GET mapping for a form. I want to get the data after the submit button is clicked, so a POST mapping – Adwait Kulkarni Mar 31 '23 at 00:56

1 Answers1

1

To send data from a Thymeleaf form to a Spring REST controller as request parameters and POST mapping, you can follow these example:

<form th:action="@{/login}" method="post">
<label>Username: <input type="text" name="username"></label><br>
<label>Password: <input type="password" name="password"></label><br>
<button type="submit">Login</button>
</form>

and for Controller

   @Controller
   public class LoginController {
    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password, Model model) {
        if ("admin".equals(username) && "admin".equals(password)) {
            System.out.printf("username:%s and password:%s", username, password);
            model.addAttribute("username", username);
            return "redirect:/success";
        }

        model.addAttribute("error", "Invalid username or password");
        return "login";
    }
}

and you can post data with

http://localhost:8080/login?username=admin&password=admin
Shahab Ranjbary
  • 303
  • 1
  • 7