侦听器预处理()未重定向到登录。html[英] Interceptor preHandle() not redirecting to login.html

问题描述

我有一个弹簧应用程序.我引入了一个 sessionInterceptor 来防止直接访问 index.jsp.如果用户没有登录,它就不能访问 index.jsp 并且应该被重定向到 login.html.该代码正在访问 preHandle() 方法并运行所有代码,但在 return false 之后它没有重定向到 login.html.怎么了?有大神帮忙吗?提前致谢.

我在 SessionInterceptor.java 中的 preHandle() 是:

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();

        // if displaying the home page, make sure the user is reloaded.
        if (request.getRequestURI().endsWith("login.html")) {
            session.removeAttribute("isUserLoggedIn");
        }

        if (session.getAttribute("isUserLoggedIn") == null && !request.getRequestURI().endsWith("login")) {
            response.sendRedirect(request.getContextPath() + "/login.html");
            return false;               
        }
        return true;
    }

我也尝试了以下方法,但都是徒劳的.

RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/login.html");
                dispatcher.forward(request, response);

我的 dispatcher-servlet.xml 设置是:

<bean id="sessionInterceptor" class="com.xxx.xxx.xxx.SessionInterceptor" />
<bean id="annotationMapper" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
    <property name="interceptors">
        <list>
            <ref bean="sessionInterceptor" />
        </list>
    </property>
</bean>

<!-- Configures Handler Interceptors -->
<mvc:interceptors>
    <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
    <mvc:interceptor>
        <mvc:mapping path="/**" />
        <bean class="com.xxx.xxx.xxx.SessionInterceptor" />
    </mvc:interceptor>
</mvc:interceptors>

web.xml 是:

  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>login.html</welcome-file>
  </welcome-file-list>

推荐答案

您可以尝试重定向到将从控制器捕获的逻辑路径试试

response.sendRedirect("/NotLogged");

然后像这样创建一个函数:

@RequestMapping(value = {"/NotLogged"}, method = RequestMethod.GET)
public String notLogged() {
    return "login.html";
}

希望对你有用!

本文地址:https://www.itbaoku.cn/post/978322.html