Spring 3.2 mvc how to rewrite url in controller as part of redirect with sent persistent status code
@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 the line I am specifying.
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 that the user's url is incorrect.
This is (assumed) the same functionality as changing the title of a question on an existing question on the stackoverflow site.
Edit by now doing below, which almost works
return new ModelAndView("redirect:/Foo/"+id+"/"+foo.getUrl());
But this returns a temporarily translated status code, I want a permanent 301.
is this a way to get both rewritten url and persistent status code using spring-mvc controllers?
source to share
Your code has
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 modelAndView.setViewName("myFoo.jsp");
effectively replaces the View value (redirectView reference) that was passed to the ModelAndView constructor. Therefore, you shouldn't call setViewName in this case.
source to share