Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To pass a Thymeleaf input value to the controller as a request parameter in Java Spring, you can follow these steps:

  1. Create a form in your Thymeleaf HTML file with the input field that you want to pass to the controller. For example, if you have an input field for a username, you can create a form like this:
<form method="post" action="/processForm">
   <label for="username">Username:</label>
   <input type="text" id="username" name="username" th:value="${username}">
   <button type="submit">Submit</button>
</form>
  1. In your Java Spring controller, create a method to handle the POST request and receive the parameter. You can use the @RequestParam annotation to specify the name of the parameter that you want to receive. For example:
@PostMapping("/processForm")
public String processForm(@RequestParam("username") String username) {
   // do something with the username parameter
   return "resultPage";
}
  1. Add a mapping for the "/processForm" URL in your Java Spring configuration. For example:
@Configuration
public class AppConfig implements WebMvcConfigurer {

   @Override
   public void addViewControllers(ViewControllerRegistry registry) {
      registry.addViewController("/").setViewName("index");
      registry.addViewController("/result").setViewName("resultPage");
   }

   @Override
   public void addFormatters(FormatterRegistry registry) {
      // add formatters if needed
   }

   @Override
   public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
      // add argument resolvers if needed
   }

   @Override
   public void addInterceptors(InterceptorRegistry registry) {
      // add interceptors if needed
   }

   @Override
   public void addResourceHandlers(ResourceHandlerRegistry registry) {
      // add resource handlers if needed
   }

}
  1. Run your application and test the form submission. When you fill in the username input field and submit the form, the controller method will receive the parameter and you can use it to perform any necessary processing.