Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot Redirect to / [duplicate]

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.

like image 597
AlanBE Avatar asked Jun 22 '26 17:06

AlanBE


1 Answers

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);
    }
like image 194
Lahiru Wijesekara Avatar answered Jun 25 '26 07:06

Lahiru Wijesekara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!