在lx-servlet beans下面添加拦截器
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/background/**"/>
<!-- 类名称 -->
<bean class="site.lx.dnf.interceptor.UserInformationInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
写一个类 site.lx.dnf.interceptor.UserInformationInterceptor 拦截器 继承 handlerInterceptorAdapter
实现ServletContextAware
public class UserInformationInterceptor extends HandlerInterceptorAdapter implements ServletContextAware{
//上下文对象
private ServletContext servletContext;
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
//获取httpSession对象
HttpSession session = request.getSession();
//从session里面获取user对象
User user = (User) session.getAttribute("user");
//如果user不为空 则返回true
if(user != null){
return true;
}
//否则还是跳转到登陆页面
response.sendRedirect(servletContext.getAttribute("contextPath")+"/login.html");
return false;
}
//servletContext的getset方法
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
public ServletContext getServletContext(){
return servletContext;
}
}