2017-04-06 195 views
0

我在applicationContext.xml的配置如下:如何使用Spring攔截或過濾器攔截資源

<mvc:annotation-driven/> 
    <context:component-scan base-package="com.lixindi.gradproject"/> 
    <mvc:resources mapping="login/**" location="login/"/> 
    <mvc:resources mapping="admin/**" location="admin/"/> 
    <mvc:resources mapping="vote/**" location="vote/"/> 

    <mvc:interceptors> 
     <mvc:interceptor> 
      <mvc:mapping path="/admin/**"/> 
      <bean class="com.lixindi.gradproject.interceptor.LoginInterceptor"/> 
     </mvc:interceptor> 
    </mvc:interceptors> 

LoginInterceptor:

public class LoginInterceptor extends HandlerInterceptorAdapter { 
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { 
     if (httpServletRequest.getSession().getAttribute("user") == null) { 
      httpServletResponse.sendRedirect("/login/login.html"); 
      System.out.println("invoked"); 
      return false; 
     } else { 
      return true; 
     } 
    } 
} 

有下的webapp多個HTML文件/管理員,我做不想通過DispatcherServlet。攔截器不攔截請求,例如,http://localhost:8080/admin/admin.html。但我希望攔截任何包含資源的網址以確保用戶已登錄。我該如何做到這一點?

謝謝@Serge Ballesta。

但是,它仍然無法攔截資源,例如,http://localhost:8080/admin/admin.html

的web.xml:

<filter> 
     <filter-name>LoginFilter</filter-name> 
     <filter-class>com.lixindi.gradproject.filter.LoginFilter</filter-class> 

    </filter> 

    <filter-mapping> 
     <filter-name>CharacterEncodingFilter</filter-name> 
     <url-pattern>/*</url-pattern> 
    </filter-mapping> 

    <filter-mapping> 
     <filter-name>LoginFilter</filter-name> 
     <url-pattern>/admin/*</url-pattern> 
    </filter-mapping> 

LoginFilter:

public class LoginFilter implements Filter { 
public void init(FilterConfig filterConfig) throws ServletException { 

} 

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 
    HttpServletRequest request = (HttpServletRequest) servletRequest; 
    HttpServletResponse response = (HttpServletResponse) servletResponse; 
    System.out.println("filter"); 
    if (request.getSession().getAttribute("user") == null) { 

     response.sendRedirect("/login/login.html"); 
    } else { 
     filterChain.doFilter(servletRequest, servletResponse); 
    } 
} 

public void destroy() { 

} 

}

回答

1

攔截器是一種專用的過濾器,它們由控制器周圍的機械用SpringMVC叫(或甚至後渲染階段)。因此,要求攔截器被調用一個未由DispatcherServlet處理的URL(這是該機器的入口點)是沒有意義的。

你將不得不使用一個普通的Java EE Filter在這裏,因爲過濾器由servlet容器

+0

得益於直接調用。但它仍然無法攔截資源。請看我更新的問題。 –