Spring Boot - redirect to a different controller method

Revansha picture Revansha · Nov 30, 2016 · Viewed 53.7k times · Source

I am creating a very basic application with SpringBoot and Thymeleaf. In the controller I have 2 methods as follows:

Method1 - This method displays all the data from the database:

  @RequestMapping("/showData")
public String showData(Model model)
{
    model.addAttribute("Data", dataRepo.findAll());
    return "show_data";
}

Method2 - This method adds data to the database:

@RequestMapping(value = "/addData", method = RequestMethod.POST)
public String addData(@Valid Data data, BindingResult bindingResult, Model model) {
    if (bindingResult.hasErrors()) {
        return "add_data";
    }
    model.addAttribute("data", data);
    investmentTypeRepo.save(data);

    return "add_data.html";
}

HTML files are present corresponding to these methods i.e. show_data.html and add_data.html.

Once the addData method completes, I want to display all the data from the database. However, the above redirects the code to the static add_data.html page and the newly added data is not displayed. I need to somehow invoke the showData method on the controller so I need to redirect the user to the /showData URL. Is this possible? If so, how can this be done?

Answer

sparrow picture sparrow · Nov 30, 2016

Try this:

@RequestMapping(value = "/addData", method = RequestMethod.POST)
public String addData(@Valid Data data, BindingResult bindingResult, Model model) {

    //your code

    return "redirect:/showData";
}