spring的过滤器可以实现登录状态问题
1.创建一个AccessFilter类,基础代码
package com.ujia.util.access; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.ujia.entity.User; public class AccessFilter implements HandlerInterceptor { @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //获取登录session User user=(User) request.getSession().getAttribute("user"); //如果访问路径为登录首页,通过 if(request.getRequestURI().startsWith(request.getContextPath()+"/user/login.htm")){ return true; } //如果请求路径为登录,通过 else if(request.getRequestURI().startsWith(request.getContextPath()+"/user/login")){ return true; } //如果没有登录session,则返回到登录页面 else if(null==user){ response.sendRedirect(request.getContextPath()+"/user/login.htm"); return false; } return true; } }
springMVC配置
<!-- 过滤器 --> <mvc:interceptors> <bean class="com.ujia.util.access.AccessFilter"></bean> </mvc:interceptors>