Spring 3.2 mvc,如何在控制器中重写 url 作为重定向视图的一部分并发送永久状态代码 [英] Spring 3.2 mvc, how to rewrite url within controller as part of redirectview with permanent status code sent
问题描述
@RequestMapping(value = "/Foo/{id}/{friendlyUrl:.*}", method = RequestMethod.GET)
public ModelAndView getFoo(@PathVariable final Long id, @PathVariable final String friendlyUrl) {
所以它匹配 ID 和任何字符串.但我希望用户看到我指定的字符串.
So it matches ID, and any string. But I want the user to see a string I specify.
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;
一切正常,除了用户看到的 url 不正确.
Everything works fine, except the url the user see's is incorrect.
它(应该是)与在 stackoverflow 站点上的现有问题上更改问题标题时具有相同的功能.
It is (supposed to be) the same functionality as when a question title gets changed on a existing question on the stackoverflow site.
编辑,现在做下面的工作
return new ModelAndView("redirect:/Foo/"+id+"/"+foo.getUrl());
但这会返回一个临时移动的状态代码,我想要永久的 301.
他们是否可以使用 spring-mvc 控制器获取重写的 url 和永久移动的状态代码?
is their a way to get both a rewritten url, and a permanently moved status code using spring-mvc controllers ?
推荐答案
在你的代码中
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(重定向视图引用)的值.所以在这种情况下你不应该调用 setViewName.
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.
这篇关于Spring 3.2 mvc,如何在控制器中重写 url 作为重定向视图的一部分并发送永久状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!