5

鉴于这种相对重定向到另一个控制器的方法:

@Controller
@RequestMapping("/someController")
public class MyController {
    @RequestMapping("/redirme")
    public String processForm(ModelMap model) {            
        return "redirect:/someController/somePage";
    }
}

鉴于我在拦截器中,如何模拟相同的相对重定向?

public class MyInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        response.sendRedirect("/someController/somePage");
        return false;
    }
}

现在有了拦截器,当我真的想在 application.com/deployment/someController/somePage 时,我将在 application.com/someController/somePage 结束。当然必须有一个“弹簧”解决方案吗?

4

3 回答 3

14

将我的评论转换为答案 -

尝试使用response.sendRedirect(request.getContextPath() + uri);

于 2012-10-19T20:54:58.083 回答
1

在参考了重定向文档,查看了 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;
    }
}
于 2012-10-19T20:36:27.777 回答
0

正如对最近的问题Context path with url-pattern redirect in spring的回答所推荐的那样,您可以使用ServletUriComponentsBuilder

于 2016-04-09T21:23:50.500 回答