Перенаправление закладок с использованием перехватчика AOP-Spring

Я пытался написать перехватчик, используя Spring AOP. Перехватчик обнаружит, является ли URL-адрес запроса закладкой, если это так, он перенаправит на страницу аутентификации. Фрагмент кода:

вызов публичного объекта (вызов MethodInvocation) throws Throwable { logger.entering (this.getClass().getSimpleName(), «вызов», вызов);

    Object result = null;
    try {
        // Logic to exclude the beans as per the list in the configuration.
        boolean excluded = false;
        for (String excludebean : excludedBeans) {
            if (excludebean != null && excludebean.equalsIgnoreCase(invocation.getThis().getClass().getSimpleName())) {
                excluded = true;
                break;
            }
        }

        // If the Target Method is "toString", then set EXCLUDE to TRUE and process the request
        if(excluded == false && invocation.getMethod().getName().equalsIgnoreCase("toString"))
        {
            excluded = true;
        }

        // if user session object is available, then process the request or
        // else forward to the configured view.
        if (excluded || getSessionHolder().getUserVO() != null) {
            result = invocation.proceed();
        }
        else {
            logger.logp(Level.INFO, this.getClass().getSimpleName(),
                    "invoke(MethodInvocation)", "User Object is "+ getSessionHolder().getUserVO()
                            + ". So redirecting user to home page");
            result = new ModelAndView("redirect:/security/authenticate.do");

        }
    }
    catch (Throwable ex) {
        throw ex;
    }
    logger.exiting(this.getClass().getSimpleName(), "invoke");
    return result;
}

Когда я отлаживаю, элемент управления входит в блок else, как и ожидалось, но после того, как я возвращаю результат, управление переходит к методу дескриптора для URL-адреса с закладкой, а не к обработчику для представления перенаправления.

Пожалуйста, помогите мне в этом .. Заранее спасибо.


person Srini    schedule 03.05.2012    source источник


Ответы (1)


Зачем нужен АОП для перехватчика. Вы можете легко перенаправить, используя обычный перехватчик.

public class RedirectInterceptor extends HandlerInterceptorAdapter{

    private String redirectMapping;

    public void setRedirectMapping(String redirectMapping) {
        this.redirectMapping = **maintenanceMapping**;
    }


    //before the actual handler will be executed
    public boolean preHandle(HttpServletRequest request, 
            HttpServletResponse response, Object handler)
        throws Exception {
                        if (somethingHappened){
            response.sendRedirect(redirectMapping);
            return false;
                        } else
                          return true;

    }
}
person danny.lesnik    schedule 03.05.2012
comment
я пробовал таким образом, у меня есть точка отладки внутри моего перехватчика, но управление никогда не приходит внутрь, я добавил свой перехватчик в ‹mvc:interceptors›.. Я использую сопоставление URL-адресов на основе аннотаций. Пожалуйста, помогите. - person Srini; 03.05.2012
comment
привет Денни, я ошибся с путем сопоставления. Теперь это работает, большое спасибо - person Srini; 06.05.2012