问题
@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