作用:当用户访问某个资源时,我们需要做一些判断,若满足条件,让用户访问资源,若不满足,则跳转到指定页面!
那如何实现呢?
首先新建一个类让其实现HandlerInterceptor,重写方法,在第一个重写的方法也就是
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException 里面做一些判断。满足条件用户可以访问资源,不满足,用户跳转到指定资源。
然后在applicationcontext.xml添加拦截路径,比如:
<!--关于拦截器的配置-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/management/**"/>
<bean id="拦截器名字" class="拦截器具体路径"/>
</mvc:interceptor>
</mvc:interceptors>
</beans>
来个具体的代码吧:
package com.imooc.reader.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class LoginInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
// 如果是登陆页面则放行
if (request.getRequestURI().contains("login")) {
return true;
}
HttpSession session = request.getSession();
// 如果用户已登陆也放行
if(session.getAttribute("user") != null) {
return true;
}
// 用户没有登陆跳转到登陆页面
request.getRequestDispatcher("/WEB-INF/ftl/management/login.ftl").forward(request, response);
return false;
}
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
拦截路径
<!--关于拦截器的配置-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/management/**"/>
<bean id="loginInterceptor" class="com.imooc.reader.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
备注一下下,复习个小知识点:获取当前访问时候的uri;
request.getRequestURI()
ok,实现了动态拦截!!!!
|