避免在控制器的请求映射方法上进行302重定向

时间:2016-01-15 08:59:43

标签: spring-mvc redirect

我使用spring 3.x和tomcat 7 我有一个带星号映射的控制器,它有一个检测重定向路径的方法。 这里:

@RequestMapping(value = "/**/t")
public class TopCategoryPageController extends AbstractSearchPageController
{
...
    //@ResponseStatus(HttpStatus.MOVED_PERMANENTLY/* this is 301 */)
    @RequestMapping(value = TOP_CATEGORY_CODE_PATH_VARIABLE_PATTERN, method = RequestMethod.GET)
    public String topCategory(@PathVariable("categoryCode") final String categoryCode, final Model model,
            final HttpServletRequest request, final HttpServletResponse response)
                    throws UnsupportedEncodingException, CMSItemNotFoundException
    {
    ...
    if any redirection 
    {
        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        return redirection;
    }   
    else
    return getViewForPage(categoryCode);
}

当请求到来时,它会执行上面的第一个topCategory方法

另外,我有一个拦截器如下。它按照预期在topCategory方法之后执行。虽然我试图在那里插入301状态,但我无法得到我想要的东西。

下面:

public class BeforeViewHandlerInterceptor extends HandlerInterceptorAdapter
{
    ...
    public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
            final ModelAndView modelAndView) throws Exception
    {
    ...
            if (isRedirectView(modelAndView))
        {
            String uri = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                    + request.getContextPath();
            uri += modelAndView.getViewName().substring(modelAndView.getViewName().indexOf(":") + 1,
                    modelAndView.getViewName().length());
            modelAndView.setViewName("redirect:" + uri);
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
            response.setHeader("Location", response.encodeRedirectURL(uri));
        }
   }

Neverthless在postHandle中设置301状态。它仍然以302重定向。

这就是我在我的页面上点击的链接:domain / context / t / categoryCode 当我分析chrome网络选项卡时,我看到第一次重定向302与其他启动器。第二个是301.注意,我需要首先重定向301.所以,我找不到它重定向302的位置.Thx和brgds

1 个答案:

答案 0 :(得分:0)

当我将代码插入控制器代码段时,如下所示,它可以正常工作。

@RequestMapping(value = "/**/t")
public class TopCategoryPageController extends AbstractSearchPageController
{
...
    @RequestMapping(value = TOP_CATEGORY_CODE_PATH_VARIABLE_PATTERN, method = RequestMethod.GET)
    public ModelAndView topCategory(@PathVariable("categoryCode") final String categoryCode, final Model model,
            final HttpServletRequest request, final HttpServletResponse response)
                    throws UnsupportedEncodingException, CMSItemNotFoundException
    {
    ...
    if any redirection 
    {
       final RedirectView redirectView = new RedirectView(redirection);
       redirectView.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
       return new ModelAndView(redirectView);
    }   
    else
       return getViewForPage(categoryCode);
}
相关问题