SpringMVC攔截器
攔截器是用來干什么的?
在一個登錄功能中,如果用戶沒有登錄卻嘗試通過地址欄直接訪問內部服務器資源,這顯然是非法的,怎樣對這些的非法訪問進行攔截? SpringMVC的攔截器可以解決這個問題,
使用攔截器
撰寫攔截器
創建攔截器類,實作HandlerInterceptor介面按需要實作preHanlder、postHanlder、afterCompeletion方法,這些方法的回傳值是boolean型,為true表示不進行攔截,false表示進行攔截,這些方法有默認實作,按需求實作即可
preHanlder方法:在訪問資源之前執行
postHanlder方法:在進行回應之前執行
afterCompeletion方法:在進行回應之后執行

public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if(request.getSession().getAttribute("name") == null){//用戶未登錄
request.setAttribute("msg","您還沒有登錄,請先登錄!");
return false;//進行攔截
}else{
return true;//不進行攔截
}
}
}
修改組態檔
修改springmvc.xml檔案
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.tzq"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<bean id="viewResolver" >
<property name="prefix" value="https://www.cnblogs.com/WEB-INF/jsp/"></property>
<property name="suffix" value="https://www.cnblogs.com/taoziblog/p/.jsp"></property>
</bean>
<!--注冊攔截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/><!--要攔截哪些路徑,/**表示攔截所有路徑-->
<mvc:exclude-mapping path="/showLogin"/><!--不進行攔截的路徑-->
<mvc:exclude-mapping path="/login"/>
<!--攔截器實作類,可以有多個,形成攔截鏈,責任鏈設計模式-->
<bean ></bean>
</mvc:interceptor>
</mvc:interceptors>
</beans>
在瀏覽器地址欄中輸入http:localhost:8080/main后,由于進行了攔截,出現404錯誤無法訪問

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/541461.html
標籤:Java
上一篇:1.Maven入門
下一篇:學習筆記——Maven的核心概念之倉庫、坐標;maven的依賴管理;Maven中統一管理版本號;Maven的繼承;Maven的聚合
