Spring 3.2 mvc,如何在控制器中重写url作为redirectview的一部分,并发送永久状态代码 [英] Spring 3.2 mvc, how to rewrite url within controller as part of redirectview with permanent status code sent

查看:350
本文介绍了Spring 3.2 mvc,如何在控制器中重写url作为redirectview的一部分,并发送永久状态代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 @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;

一切正常,但用户看到的网址不正确。

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控制器获取重写网址和永久移动状态代码的方法吗?

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(redirectView引用)的值。
所以在这种情况下你不应该调用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作为redirectview的一部分,并发送永久状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆