hankuk
hankuk

Reputation: 41

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>

Upvotes: 1

Views: 3654

Answers (2)

Shervin Zadsoroor
Shervin Zadsoroor

Reputation: 92

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;

Upvotes: 0

Metroids
Metroids

Reputation: 20477

  1. th:object (generally) isn't used for get requests. You use th:object when you're submitting (w/POST) a form, and you want Spring to populate the properties of a Java object with the fields on that form.
  2. Since Thymeleaf is a server side processed language, and normal html doesn't support building/forwarding to the kind of url you want you're going to have to use JavaScript to accomplish what you want.

For example, a normal GET request when submitted through a form looks like this:

/searchMovies?property1=value1&property2=value2

if you want your url to look like this:

/searchMovies/value1

then you need to use JavaScript to build that url when the user clicks the button and forward to that url.

Upvotes: 1

Related Questions