use*_*611 35 java spring-mvc restful-url
我正在尝试重定向,而不将参数添加到我的URL.
@Controller
...
public class SomeController
{
...
@RequestMapping("save/")
public String doSave(...)
{
...
return "redirect:/success/";
}
@RequestMapping("success/")
public String doSuccess(...)
{
...
return "success";
}
Run Code Online (Sandbox Code Playgroud)
重定向后,我的网址看起来总是这样:.../success/?param1=xxx¶m2=xxx.由于我希望我的URL有点RESTful,并且在重定向后我从不需要params,我不希望它们被添加到重定向上.
任何想法如何摆脱它们?
axt*_*avt 32
在Spring 3.1中,控制此行为的首选方法是向方法添加RedirectAttributes参数:
@RequestMapping("save/")
public String doSave(..., RedirectAttributes ra)
{
...
return "redirect:/success/";
}
Run Code Online (Sandbox Code Playgroud)
默认情况下,它禁用属性添加,并允许您控制要显式添加的属性.
在以前的Spring版本中,它更复杂.
小智 31
在Spring 3.1中,使用ignoreDefaultModelOnRedirect选项禁用自动将模型属性添加到重定向:
<mvc:annotation-driven ignoreDefaultModelOnRedirect="true" />
Run Code Online (Sandbox Code Playgroud)
Lu5*_*u55 10
添加RedirectAttributes参数对我不起作用(可能是因为我的HandlerInterceptorAdapter在模型中添加了一些东西),但这种方法确实如此(感谢@ reallynic的评论):
@RequestMapping("save/")
public View doSave(...)
{
...
RedirectView redirect = new RedirectView("/success/");
redirect.setExposeModelAttributes(false);
return redirect;
}
Run Code Online (Sandbox Code Playgroud)
在Spring 4中,有一种方法可以使用注释在java配置中执行此操作.我正在分享它,以防任何人需要它,因为我需要它.
在扩展的配置类上WebMvcConfigurerAdapter,您需要添加:
@Autowired
private RequestMappingHandlerAdapter requestMappingHandlerAdapter;
@PostConstruct
public void init() {
requestMappingHandlerAdapter.setIgnoreDefaultModelOnRedirect(true);
}
Run Code Online (Sandbox Code Playgroud)
有了这个,你不需要使用RedirectAttributes,它在java配置中与Matroskin的答案相同.
如果您使用的是Spring 3.1,则可以使用Flash Scope,否则您可以在此处查看最多投票(未接受)答案中使用的方法:
Spring MVC Controller使用URL参数重定向而不是响应
编辑:
3.1用户的好文章:
http://www.tikalk.com/java/redirectattributes-new-feature-spring-mvc-31
非3.1用户的解决方法:
| 归档时间: |
|
| 查看次数: |
34491 次 |
| 最近记录: |