Search code examples
javaspringspring-bootthymeleaf

How to hide model data from URL in thymeleaf?


Here is some code:

1.

@GetMapping(path = "/register", produces = MediaType.TEXT_HTML_VALUE)
public String register(@RequestParam("name") String name,
    RedirectAttributes redirectAttributes) {
    // call to service
    redirectAttributes.addAttribute("name", name);
    return "redirect:/success";
}

This endpoint gets hit first and registers the user with provided name and redirects to the success page. It also supplies the user name.

2.

@GetMapping(value = "/success", produces = MediaType.TEXT_HTML_VALUE)
public String success(@ModelAttribute("name") String name, Model model) {
    model.addAttribute("name", name);
    return "success";
}

This endpoint changes the path in browser URL tab to /success and displays success.html template. It also sets the username in model so that on we can show on UI that ${name} registered successfully.

success.html is a template in /templates folder, which we want to show once this operation is over on /success page.

Everything works as expected. The problem? name of the use shows up in URL on /success page.

So after registration, while we expect the URL to be just /success, it actually is /success?name=John. It is possible to hide the request parameter part? Or to send the data in body somehow rather than request parameter.

Thanks in advance, let me know if any other detail is required.


Solution

  • Sure. It can be done for example by using redirectAttributes.addFlashAttribute("name", name) instead of redirectAttributes.addAttribute("name", name) in the first controller.

    You can get more info here.