javaspringformsthymeleafhttp-request-parameters

How to send a Thymeleaf input value as a request parameter to controller in Java Spring?


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


Solution

  • 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