1.在pom.xml文件中添加jar包(或者直接百度搜索spring-webmv下载jar包引用)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
2.在ApplicationContext.xml中配置拦截器引用(引用自定义拦截器)
(1)在beans中引用(不然不认识mvc标签)
xmlns:mvc="http://www.springframework.org/schema/mvc"
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
(2)在beans里面添加以下标签
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<mvc:interceptors>
<!-- 访问拦截 -->
<mvc:interceptor>
<mvc:mapping path="/**/**" />
<!--login方法不会被此浏览器拦截-->
<mvc:exclude-mapping path="/login" />
<!--自定义拦截器相对路径-->
<bean class="com.hbvat.web.interceptor.LoginHandlerInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
3在相应的com.hbvat.web.intercepto包下创建LoginHandlerInterceptor文件继承HandlerInterceptorAdapter接口重写preHandle方法(记得要加@Override实现重写呀)
public class VersionInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if(1==2){//判断条件 为未登录
response.sendRedirect(request.getContextPath() + "/login“);//跳转登陆页
response.getSession.setAttribute("mingcheng",true);
return false;//false不执行当前浏览器路径
}
return true;//true执行浏览器路径,
}
}
4.验证拦截器是是否存在,在登陆成功前验证session中是否存在某值
session.getAttribute("mingcheng");
此session中赋值的方法只能在此拦截器;