Spring Boot - redirect to a different controller m

2019-03-18 17:46发布

I am very new to Spring Boot. 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?

Thanks in advance.

3条回答
趁早两清
2楼-- · 2019-03-18 18:07

sparrow's solution did not work for me. It just rendered the text "redirect:/"

I was able to get it working by adding HttpServletResponse httpResponse to the controller method header.

Then in the code, adding httpResponse.sendRedirect("/"); into the method.

Example:

@RequestMapping("/test")
public String test(@RequestParam("testValue") String testValue, HttpServletResponse httpResponse) throws Exception {
    if(testValue == null) {
        httpResponse.sendRedirect("/");
        return null;
    }
    return "<h1>success: " + testValue + "</h1>";
}
查看更多
Animai°情兽
3楼-- · 2019-03-18 18:12

You should return a http status code 3xx from your addData request and put the redirct url in the response.

查看更多
太酷不给撩
4楼-- · 2019-03-18 18:30

Try this:

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

    //your code

    return "redirect:/showData";
}
查看更多
登录 后发表回答