攔截器配置
在springMVC-servlet.xml配置文件中增加以下配置
<!-- 攔截器 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<!-- mvc:exclude-mapping(不攔截請求信息配置) -->
<mvc:exclude-mapping path="/admin/isExist.html"/>
<mvc:exclude-mapping path="/page/*"/>
<mvc:exclude-mapping path="/page/*/*"/>
<bean id="sessionInterceptor" class="com.yq.util.SessionInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
- "mvc:exclude-mapping"爲不攔截請求配置,可以是某一個某一個請求(/admin/isExist.html),亦可以使用通配符批量設置(/page/*)
- “SessionInterceptor”,爲攔截請求之後的處理類
SessionInterceptor類處理
/**
* @program: weixin
* @description: 攔截器
* @author: Mr.Jkx
* @create: 2019-09-07 11:37
*/
public class SessionInterceptor implements HandlerInterceptor {
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handel) throws Exception {
HttpSession session = req.getSession();
// 從session當中獲取特定的數據
Object obj = session.getAttribute("username");
if (obj == null || obj == "") {
// 未登錄,重定向到登錄頁面
res.sendRedirect("攔截之後的重定向請求路徑");
return false;
}
// 已登錄,繼續向後調用
return true;
}
- preHandle在業務處理器處理請求之前被調用;如果返回false,則請求不再往下處理。
- postHandle在業務處理器處理請求執行完成後,生成視圖之前執行;
- afterCompletion在DispatcherServlet完全處理完請求後被調用,可用於清清理資源,afterCompletion()執行完成後開始渲染頁面