Dynamically genereated URL of a .html file using Spring Boot and Thymeleaf

Viewed 14

I'm fairly new to Thymeleaf and Spring Boot. I'm looking to direct users to a dynamically generated URL that includes their birth date, like http://localhost:8080/born-on-05-05-1955. For this purpose I'm getting the user's details in a web form using Thymeleaf and then attempt to redirect them based on the information they entered.

If I manually enter the URL http://localhost:8080/born-on-5-5-1955, it successfully displays the page. I presume that's based on the RequestMapping I've set up:

@RequestMapping(value = {"/born-on-{birthDate}"})
public String displayBirthDatePage(@PathVariable("birthDate") final String birthDateInURL, Model model) {
  // add attributes to model
  return "born-on.html";
}

When I try to redirect users to that page though (by transmitting the data from the form through a POST request to http://localhost:8080/dateofbirth), the redirect fails: org.thymeleaf.exceptions.TemplateInputException: Error resolving template [born-on-5-5-1955], template might not exist or might not be accessible by any of the configured Template Resolvers

My redirect that receives the POST request looks as follows:

  @PostMapping("/dateofbirth")
  public String submitForm(@ModelAttribute("birthDate") final String userBirthDate) {
    LocalDate birthDate = LocalDate.parse(userBirthDate);
    return "geboren-am-"
        + birthDate.getDayOfMonth()
        + "-"
        + birthDate.getMonthValue()
        + "-"
        + birthDate.getYear();
  }

It looks like my redirect is trying to find the non-existent template in /projectfolder/src/main/resources/templates instead of using the RequestMapping to resolve the path.

I've attempted changing the returned String to a ModelandView object to fix this. While that actually displays the correct page instead of an Error, the URL does not update and keeps showing the old URL http://localhost:8080/dateofbirth:

  @PostMapping("/born-on")
  public ModelAndView submitForm(@ModelAttribute("birthDate") final String userBirthDate) {
    LocalDate birthDate = LocalDate.parse(userBirthDate);
    return new ModelAndView("forward:born-on-"
        + birthDate.getDayOfMonth()
        + "-"
        + birthDate.getMonthValue()
        + "-"
        + birthDate.getYear());
  }

How do I get to this forward to work so it also shows the correct URL http://localhost:8080/born-on-5-5-1955 in the user's browser?

0 Answers
Related