1.拦截器类
package com.intercept;
import java.net.URI;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class LoginInterceptor implements HandlerInterceptor {
//处理拦截,在Controller处理之前执行,返回true拦截器往下指向,false时结束整个请求
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
// TODO Auto-generated method stub
/*
* 判断是否已登录,如果没有登录返回登录界面,如果登录了放行
* 如果是登录请求,也需要放行
*/
//获取请求的路径进行判断
String url = request.getRequestURI();
System.out.println(url);
//判断请求是否需要拦截
if(url.indexOf("/login") >= 0){
return true;
}
HttpSession session = request.getSession();
String user_session = (String)session.getAttribute("USER_SESSION");
if(user_session !=null && user_session != "")
return true;
request.setAttribute("msg", "用户尚未登录");
request.getRequestDispatcher("login.jsp").forward(request, response);
return false;
}
//在Controller的方法调用之后执行,可以对ModelAndView操作,只有当preHandle方法返回true时才执行
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
}
//在整个请求完成之后执行,主要作用是清理资源,只有当preHandle方法返回true时才执行
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub
}
}
2.springmvc配置文件(下面是配置了三个拦截器,上面只复制了关键的代码)
<mvc:interceptors>
<!--
下面两个写法等价
<bean class="com.intercept.FirstInterceptor"></bean> -->
<!-- FirstInterceptor拦截所有URI请求 -->
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.intercept.FirstInterceptor"></bean>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/hello"/>
<bean class="com.intercept.SecondInterceptor"></bean>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.intercept.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>