Spring Boot Redirect to /

AlanBE :

I would like to redirect the user to "/" page.

In my controller, I have:

    @RequestMapping(value = "/uploadImage", method = {RequestMethod.POST})
    public ModelAndView addUser (@RequestParam(value="file") MultipartFile file,
            HttpServletRequest request,
            ModelMap model) {
    ...
    if (...) { 
            model.addAttribute("uploadFileError", true);
            return new ModelAndView("/", model);
    } 
    return new ModelAndView("/", model);

and in my receiving page:

    @RequestMapping(value = "/")
    public String root(Model model, HttpServletRequest request) {
    ...
    return "index";
    }

but Spring returns "Error resolving template [/], template might not exist or might not be accessible by any of the configured Template Resolvers"

Please help. Thanks.

Lahiru Wijesekara :

As per the explanation given it seems like you need to redirect to some other controller in the same server. Below code will suits you to manage this.

@RequestMapping(value = "/uploadImage", method = { RequestMethod.POST })
    public ModelAndView addUser(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request,
            ModelMap model) {

        return new ModelAndView("redirect:/", model);
    } 

For further reading you can refer to below differences of redirect and forward

Forward:

  1. The request will be further processed on the server side

  2. The client isn’t impacted by forward, URL in a browser stays the same

  3. Request and response objects will remain the same object after forwarding.

  4. Request-scope objects will be still available

Redirect:

  1. The request is redirected to a different resource
  2. The client will see the URL change after the redirect
  3. A new request is created
  4. Redirect is normally used within Post/Redirect/Get web development pattern

If you just want to test the redirection run below without MultipartFile @AlanBE

@RequestMapping(value = "/uploadImage", method = { RequestMethod.POST })
    public ModelAndView addUser(/* @RequestParam(value = "file") MultipartFile file, */ HttpServletRequest request,
            ModelMap model) {

        return new ModelAndView("redirect:/", model);
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=108703&siteId=1