在spring-mvc中使用标签
<mvc:interceptors>
<mvc:interceptor>
<!--默认拦截的连接-->
<mvc:mapping path="/*"/>
<!--不拦截的连接-->
<mvc:exclude-mapping path="/login"/>
<bean class="com.chen.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
创建自定义拦截器
package com.chen.interceptor;
import com.chen.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpSession;
/**
* Created by Administrator on 2017/2/21 0021.
*/
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception {
//首先进入的方法
System.out.println("preHandle");
//return false表示拦截,不向下执行
//return true表示放行
System.out.println(request.getServletPath());
HttpSession session = request.getSession();
User u=(User)session.getAttribute("userInfo");
if(u!=null){
return true;
}else{
return false;
}
}
//返回modelAndView之前执行
@Override
public void postHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
}
//执行Handler完成执行此方法
@Override
public void afterCompletion(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion");
}
}