简体   繁体   中英

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) {

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM