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?
Send to another route in Spring Boot To make a redirect, simply create the method in the Controller and return a String .
Like 'redirect:' prefix , Spring also allows to use special directive 'forward:' to return forwarded url as String. On encountering this special prefix in the return value of a controller, Spring uses javax. servlet. RequestDispatcher#forward to forward a request from one controller to another .
Try this:
@RequestMapping(value = "/addData", method = RequestMethod.POST) public String addData(@Valid Data data, BindingResult bindingResult, Model model) { //your code return "redirect:/showData"; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With