1.写一个拦截器,实现HandlerInterceptor接口
/**
* Created by Jujung
* Date : 2019/9/23 19:40
* 登录拦截器
*/
public class LoginInterceptor implements HandlerInterceptor {
/**
* 处理进入handler之前的请求
* @param request
* @param response
* @param o
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
String requestURL = request.getRequestURL().toString();
// 请求中包含login
boolean login = requestURL.contains("/login");
// 请求中包含logout
boolean logout = requestURL.contains("/logout");
if( login || logout){
return true;
}else{
HttpSession session = request.getSession();
Object user = session.getAttribute("loginUser");
if(user != null){
return true;
}
}
response.sendRedirect("/login.action");
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
}
}
2.在springmvc的配置文件中配置该拦截器
<!-- 配置拦截器-->
<mvc:interceptors>
<!--可以配置多个拦截器按顺序执行-->
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.jujung.bos.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>