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() {
}
}
得益於直接調用。但它仍然無法攔截資源。請看我更新的問題。 –