Spring 3.2 MVC,如何使用永久状态代码发送重定向视图中的控制器重写URL
问题内容:
@RequestMapping(value = "/Foo/{id}/{friendlyUrl:.*}", method = RequestMethod.GET)
public ModelAndView getFoo(@PathVariable final Long id, @PathVariable final String friendlyUrl) {
因此它匹配ID和任何字符串。但是我希望用户看到我指定的字符串。
foo = fooService.get(id); //use id from pathvariable
redirectView = new RedirectView(foo.getCorrectUrl()); //set url to correct url, not that in path
redirectView.setStatusCode(HttpStatus.MOVED_PERMANENTLY); //moved permanently
modelAndView = new ModelAndView(redirectView);
modelAndView.setViewName("myFoo.jsp");
return modelAndView;
一切正常,除了用户看到的网址不正确。
(假定)与在stackoverflow网站上的现有问题上更改问题标题时具有相同的功能。
编辑,现在做下面的工作差不多了
return new ModelAndView("redirect:/Foo/"+id+"/"+foo.getUrl());
但这返回一个临时移动的状态代码,我希望永久为301。
使用spring-mvc控制器获取重写的URL和永久移动的状态代码的方法是什么?
问题答案:
在您的代码中
foo = fooService.get(id); //use id from pathvariable
redirectView = new RedirectView(foo.getCorrectUrl()); //set url to correct url, not that in path
redirectView.setStatusCode(HttpStatus.MOVED_PERMANENTLY); //moved permanently
modelAndView = new ModelAndView(redirectView);
modelAndView.setViewName("myFoo.jsp");
return modelAndView;
对的调用modelAndView.setViewName("myFoo.jsp");
有效地替换了传递给ModelAndView构造函数的View的值(redirectView引用)。因此,在这种情况下,您不应调用setViewName。