一)在springMvc核心配置文件中配置
<!-- 配置拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<!-- 释放静态资源 -->
<mvc:exclude-mapping path="/js/**" />
<mvc:exclude-mapping path="/css/**" />
<!-- 拦截器路径 -->
<bean class="com.oracle.sm.interceptor.IntercePtor"></bean>
</mvc:interceptor>
</mvc:interceptors>
二)新创建一个包 com.oracle.sm.interceptor,创建一个IntercePtor类
重写三个方法
preHandle:进入处理器之前进入
// 获取请求路径
String path = request.getRequestURI();
// 登录操作,不能拦截
if (path.contains("user")) {
System.err.println("包含关键url,user放行");
return true;
} else {
// 取到当前用户的session对象
HttpSession session = request.getSession(false);
if (session != null) {
if (session.getAttribute("user") != null) {
System.err.println("用户已经登录,放行");
return true;
} else {
response.sendRedirect(request.getContextPath() + "/user/dologin.action");
System.err.println("未登录被拦截");
}
} else {
response.sendRedirect(request.getContextPath() + "/user/dologin.action");
System.err.println("未登录被拦截");
}
}
return false;
postHandle:进入处理器,返回视图给核心控制器的时候,拦截(暂无代码演示)
afterCompletion:请求处理全部处理完成之后会被该方法拦截
System.out.println("视图渲染完毕,此次拦截结束");
//可以对异常进行统一处理
if(ex!=null){
log.equals(ex.getMessage());
}
三)配置web.xml文件
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/pages/exception/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/WEB-INF/exception/500.jsp</location>
</error-page>
四)修改log4j.properties中的文件
log4j.rootCategory=DEBUG,stdout,logfile