Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot - redirect to a different controller method

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?

like image 929
Revansha Avatar asked Nov 30 '16 05:11

Revansha


People also ask

How do I redirect in spring boot rest?

Send to another route in Spring Boot To make a redirect, simply create the method in the Controller and return a String .

How do I forward a spring controller?

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 .


1 Answers

Try this:

@RequestMapping(value = "/addData", method = RequestMethod.POST) public String addData(@Valid Data data, BindingResult bindingResult, Model model) {      //your code      return "redirect:/showData"; } 
like image 157
sparrow Avatar answered Sep 30 '22 10:09

sparrow