首先在springmvc中配置拦截器
<!-- 配置拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<!-- 拦截所有mvc控制器 -->
<mvc:mapping path="/**"/>
<!-- mvc:exclude-mapping是另外一种拦截,它可以在你后来的测试中对某个页面进行不拦截,这样就不用在
LoginInterceptor的preHandler方法里面获取不拦截的请求uri地址了(优选) -->
<mvc:exclude-mapping path="/admin/loginPage.action" />
<mvc:exclude-mapping path="/admin/varifyCode.action" />
<bean class="nyist.admin.utils.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
然后写拦截器:
public class LoginInterceptor implements HandlerInterceptor { @Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub } @Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub } @Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
HttpSession session = arg0.getSession();
//String uri = request.getRequestURI(); // 获取登录的uri,这个是不进行拦截的
//if(session.getAttribute("LOGIN_USER")!=null || uri.indexOf("system/login")!=-1) {// 说明登录成功 或者 执行登录功能
if(session.getAttribute("admin")!=null) {
// 登录成功不拦截
return true;
}else {
// 拦截后进入登录页面
arg1.sendRedirect(arg0.getContextPath()+"/admin/loginPage.action");
return false;
}
}
}
拦截器这样就设置好了