为了防止用户在不登录的情况下通过并接请求直接访问系统,我们需要通过session和拦截器来防止这样的情况。
拦截器的配置:
为拦截器建立一个包:interceptor,并在包里建立 LoginInterceptor 拦截器类
拦截器需要 implements HandlerInterceptor,并实现 HandlerInterceptor 的方法:
/**
* 登录拦截器
*/
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
HttpSession session = httpServletRequest.getSession();
if ( session.getAttribute("LOGIN_USER") != null ){
return true;
}else {
httpServletResponse.sendRedirect( httpServletRequest.getContextPath() + "/gradu/dologin");
return false;
}
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
配置spring-mvc文件:
<!--拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<mvc:exclude-mapping path="/gradu/dologin" />
<bean class="com.hwl.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
注意:
<mvc:mapping path="/**"/> 是已经拦截了所有请求,包括登录,
如果后来想不拦截某个页面,就添加:<mvc:exclude-mapping path="/system/login" />
另外。记得登录时添加session。