来自HttpServletResponse的Spring MVC相对重定向

时间:2012-10-19 20:10:47

标签: java spring spring-mvc

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

@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。当然必须有一个“弹簧”解决方案吗?

3 个答案:

答案 0 :(得分:13)

将我的评论转换为答案 -

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

答案 1 :(得分:1)

在引用redirect documentation,查看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;
    }
}

答案 2 :(得分:0)

根据对最新问题Context path with url-pattern redirect in spring的回答建议,您可以使用ServletUriComponentsBuilder