Spring Boot - redirect to a different controller method

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

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.


Try this:

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

    //your code

    return "redirect:/showData";
}