拦截器在SSM中的简单应用
一、创建一个类,实现拦截器接口HandlerInterceptor
public class CheckInterceptor implements HandlerInterceptor{ /** * 执行最晚,做一些释放资源的工作 */ @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { // TODO Auto-generated method stub } /** * 在拦截器放行之后执行, */ @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { // TODO Auto-generated method stub } /** * 在进入拦截器之前执行,返回true就放行,继续请求控制器,返回false,就不执行 */ @Override public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception { User user = (User) arg0.getSession().getAttribute("user"); if(user!=null){ return true; }else{ arg1.sendRedirect("../login.jsp"); return false; } } }
二、在spring核心配置文件配置
<!-- 拦截器 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/jsp/*"/> <bean class="com.tools.CheckInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>