Spring Boot - redirect to a different controller method

浪尽此生 提交于 2019-12-31 12:18:32

问题


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.


回答1:


Try this:

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

    //your code

    return "redirect:/showData";
}



回答2:


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>";
}



回答3:


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




回答4:


Below Solution worked for me. getAllCategory() method displays the data and createCategory() method add data to the database. Using return "redirect:categories";, will redirect to the getAllCategory() method.

@GetMapping("/categories")
public String getAllCategory(Model model) {
    model.addAttribute("categories",categoryRepo.findAll());
    return "index";
}

@PostMapping("/categories")
public String createCategory(@Valid Category category) {

    categoryRepo.save(category);
    return "redirect:categories";
}

OR using ajax jQuery also it is possible.



来源:https://stackoverflow.com/questions/40880772/spring-boot-redirect-to-a-different-controller-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!