Search code examples
springspring-datathymeleaf

Thymeleaf th:object does not work with controller?


I am new to Thymeleaf. I am trying to create a search form but it doesn't work. But when I tried manually entering localhost:8080/searchMovies/name and it works fine, so whats wrong with my code?

MovieController.java

@GetMapping("/searchMovies/{name}")
    public ModelAndView searchMoviesByNameLike(@PathVariable("name") String name) {
        List<Movie> searchMovies = movieService.findMovieByNameContaining(name);
        ModelAndView modelAndView = new ModelAndView("searchMovies");
        modelAndView.addObject("searchMovies", searchMovies);
        modelAndView.addObject("searchMoviesList", movieService.findMovieByNameContaining(name));
        return modelAndView;
}

header.html

<form th:object="${searchMovies}"  th:action="@{/searchMovies}" method="get"  class="form-inline my-2 my-lg-0">
   <input class="form-control mr-sm-2" type="text" placeholder="" aria-label="Search" th:value="${name}">
   <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>

Solution

  • you need a name at the end of url but in you didn't set it. in this case you can't set it. you must do it by a different approach. another thing is that you need an object in your form not a list. try the following code :

    @GetMapping("/searchMovies")
    public String sendSearchForm(Model model) {
        model.addAttribute("movie", new Movie());
        return "search";
    }
    
    <form th:object="${movie}"  th:action="@{/searchMovies}" method="post"     class="form-inline my-2 my-lg-0">
     <input class="form-control mr-sm-2" type="text" placeholder="" aria-label="Search" th:field="*{name}">
     <button class="btn btn-outline-success my-2 my-sm-0"  type="submit">Search</button>
    </form>
    
    
    @PostMapping("/searchMovie")
    public String searchAccounts(@ModelAttribute Movie movie) {
        List<Movie> searchMovies =  movieService.findMovieByNameContaining(movie.getName());
    .
    .
    .
        return modelAndView;