2
 @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 和永久移动状态代码的方法吗?

4

1 回答 1

4

在您的代码中,您有

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;

The call to modelAndView.setViewName("myFoo.jsp"); effectively replaces the value of View (redirectView reference) that was passed to ModelAndView contructor. So you should not call setViewName in this case.

于 2012-12-30T11:18:06.587 回答