java 来自 HttpServletResponse 的 Spring MVC 相对重定向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12981754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring MVC Relative Redirect from HttpServletResponse
提问by Vetsin
Given this methodology of relative redirect to another controller:
鉴于这种相对重定向到另一个控制器的方法:
@Controller
@RequestMapping("/someController")
public class MyController {
@RequestMapping("/redirme")
public String processForm(ModelMap model) {
return "redirect:/someController/somePage";
}
}
How can I simulate that same relativeredirect given that I'm within an interceptor?
鉴于我在拦截器中,如何模拟相同的相对重定向?
public class MyInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
{
response.sendRedirect("/someController/somePage");
return false;
}
}
Now with the interceptor, i will end up at application.com/someController/somePage when I really want to be at application.com/deployment/someController/somePage. Surely there must be a 'spring' solution for this?
现在有了拦截器,当我真的很想访问 application.com/deployment/someController/somePage 时,我最终会访问 application.com/someController/somePage。当然,必须有一个“弹簧”解决方案吗?
回答by devang
Converting my comment to an answer -
将我的评论转换为答案 -
Try using response.sendRedirect(request.getContextPath() + uri);
尝试使用 response.sendRedirect(request.getContextPath() + uri);
回答by Vetsin
After referencing the redirect documentation,reviewing the source code for UrlBasedViewResolver, and gotuskar's comment, I feel silly for not knowing this would work and have a solution:
在参考了重定向文档,查看了 UrlBasedViewResolver 的源代码和 gotuskar 的评论后,我感到很傻,因为不知道这会起作用并有解决方案:
public class MyInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
{
StringBuilder targetUrl = new StringBuilder();
if (this.redirectURL.startsWith("/")) {
// Do not apply context path to relative URLs.
targetUrl.append(request.getContextPath());
}
targetUrl.append(this.redirectURL);
if(logger.isDebugEnabled()) {
logger.debug("Redirecting to: " + targetUrl.toString());
}
response.sendRedirect(targetUrl.toString());
return false;
}
}
回答by Stewart
As recommended by an answer to the more recent question Context path with url-pattern redirect in spring, you could use ServletUriComponentsBuilder
正如最近问题Context path with url-pattern redirect in spring的答案所推荐的那样,您可以使用ServletUriComponentsBuilder