Spring MVC Controller: Redirect without parameters being added to my url

后端 未结 6 405
伪装坚强ぢ
伪装坚强ぢ 2020-11-30 04:58

I\'m trying to redirect without parameters being added to my URL.

@Controller
...
public class SomeController
{
  ..         


        
相关标签:
6条回答
  • 2020-11-30 05:02

    Adding RedirectAttributes parameter doesn't work for me (may be because my HandlerInterceptorAdapter adds some stuff to model), but this approach does (thanks to @reallynic's comment):

    @RequestMapping("save/")
    public View doSave(...)
    {
        ...
        RedirectView redirect = new RedirectView("/success/");
        redirect.setExposeModelAttributes(false);
        return redirect;
    }
    
    0 讨论(0)
  • 2020-11-30 05:03

    In Spring 4 there is a way to do this with java config, using annotations. I'm sharing it in case anyone needs it as I needed it.

    On the config class that extends WebMvcConfigurerAdapter, you need to add:

    @Autowired
    private RequestMappingHandlerAdapter requestMappingHandlerAdapter;
    
    
    @PostConstruct
    public void init() {
        requestMappingHandlerAdapter.setIgnoreDefaultModelOnRedirect(true);
    }
    

    With this, you do not need to use RedirectAttributes, and it is an equivalent in java config to Matroskin's answer.

    0 讨论(0)
  • 2020-11-30 05:09

    In Spring 3.1 a preferred way to control this behaviour is to add a RedirectAttributes parameter to your method:

    @RequestMapping("save/")
    public String doSave(..., RedirectAttributes ra)
    {
        ...
        return "redirect:/success/";
    }
    

    It disables addition of attributes by default and allows you to control which attributes to add explicitly.

    In previous versions of Spring it was more complicated.

    0 讨论(0)
  • 2020-11-30 05:15

    In Spring 3.1 use option ignoreDefaultModelOnRedirect to disable automatically adding model attributes to a redirect:

    <mvc:annotation-driven ignoreDefaultModelOnRedirect="true" />
    
    0 讨论(0)
  • 2020-11-30 05:15

    Try this:

    public ModelAndView getRequest(HttpServletRequest req, Locale locale, Model model) {
    
        ***model.asMap().clear();*** // This clear parameters in url
    
        final ModelAndView mav = new ModelAndView("redirect:/test");
    
        return mav;
    }
    
    0 讨论(0)
  • 2020-11-30 05:18

    If you're using Spring 3.1, you can use Flash Scope, otherwise you can take a look at the method used in the most voted (not accepted) answer here:

    Spring MVC Controller redirect using URL parameters instead of in response

    EDIT:

    Nice article for 3.1 users:

    http://www.tikalk.com/java/redirectattributes-new-feature-spring-mvc-31

    Workaround for non-3.1 users:

    Spring MVC custom scope bean

    0 讨论(0)
提交回复
热议问题