Spring 3.2 mvc, how to rewrite url within controller as part of redirectview with permanent status code sent

大兔子大兔子 提交于 2019-12-31 02:50:07

问题


 @RequestMapping(value = "/Foo/{id}/{friendlyUrl:.*}", method = RequestMethod.GET)
 public ModelAndView getFoo(@PathVariable final Long id, @PathVariable final String friendlyUrl) {

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;

Everything works fine, except the url the user see's is incorrect.

It is (supposed to be) the same functionality as when a question title gets changed on a existing question on the stackoverflow site.

Edit, now doing the below that almost works

  return new ModelAndView("redirect:/Foo/"+id+"/"+foo.getUrl());

But that returns a temporarily moved status code, I want permanent 301.

is their a way to get both a rewritten url, and a permanently moved status code using spring-mvc controllers ?


回答1:


In your code you have

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.



来源:https://stackoverflow.com/questions/14089885/spring-3-2-mvc-how-to-rewrite-url-within-controller-as-part-of-redirectview-wit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!