Spring-MVC controller redirect to “previous” page?

后端 未结 7 1000
无人共我
无人共我 2021-01-31 18:34

Let\'s say I\'ve got a form for editing the properties of a Pony, and in my web application there are multiple places where you can choose to edit a Pony. For instance, in a li

7条回答
  •  星月不相逢
    2021-01-31 19:18

    My answer is alike to Sam Brodkins´s (i recomended it also). But having in count that the "Referer" value may not be available i made this function to use it in my controllers

    /**
    * Returns the viewName to return for coming back to the sender url
    *
    * @param request Instance of {@link HttpServletRequest} or use an injected instance
    * @return Optional with the view name. Recomended to use an alternativa url with
    * {@link Optional#orElse(java.lang.Object)}
    */
    protected Optional getPreviousPageByRequest(HttpServletRequest request)
    {
       return Optional.ofNullable(request.getHeader("Referer")).map(requestUrl -> "redirect:" + requestUrl);
    }
    

    So in your controller caller function you should return something like this:

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public @ResponseBody
    String testRedirection(HttpServletRequest request)
    {
          //Logic....
          //Returns to the sender url
          return getPreviousPageByRequest(request).orElse("/"); //else go to home page
    }
    

提交回复
热议问题