您好,登錄后才能下訂單哦!
自定義攔截器類
public class SessionInterceptor extends HandlerInterceptorAdapter {
public SessionInterceptor() {
// TODO Auto-generated constructor stub
}
private List<String> excludedUrls;
//通過屬性注冊不需要過濾的url list
public void setExcludedUrls(List<String> excludedUrls) {
this.excludedUrls = excludedUrls;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String requestUrl = request.getRequestURI();
//排除不需要過濾的URL
for(String url:excludedUrls) {
if(requestUrl.endsWith(url)) {
return true;
}
}
//獲取當(dāng)前的會話session
HttpSession session = request.getSession();
if(session.getAttribute("userid") == null) {
//若登錄session過期或不存在就跳轉(zhuǎn)到login頁面
request.getRequestDispatcher("/login.jsp").forward(request, response);
return false;
}
return true;
}
}
springmvc-servlet.xml 攔截器注冊
<mvc:interceptors>
<mvc:interceptor>
<!--
/*的意思是所有文件夾及里面的子文件夾
/是所有文件夾,不含子文件夾
/是web項(xiàng)目的根目錄
-->
<mvc:mapping path="/**" />
<!-- 需排除攔截的地址 -->
<!-- <mvc:exclude-mapping path="/login"/> -->
<bean id="commonInterceptor" class="com.skcc.chart.interceptor.SessionInterceptor">
<property name="excludedUrls">
<list>
<value>/login</value>
</list>
</property>
</bean> <!--這個類就是我們自定義的Interceptor -->
</mvc:interceptor>
<!-- 當(dāng)設(shè)置多個攔截器時,先按順序調(diào)用preHandle方法,然后逆序調(diào)用每個攔截器的postHandle和afterCompletion方法 -->
</mvc:interceptors>
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<mvc:resources mapping="/resources/**" location="/resources/" order="0" />
<mvc:resources mapping="/js/**" location="/js/" order="0" />
<mvc:resources mapping="/css/**" location="/css/" order="0" />
<!-- Spring MVC不處理靜態(tài)資源 -->
<mvc:default-servlet-handler />
<!-- 配置注解的處理器映射器和處理器適配器 -->
<mvc:annotation-driven ></mvc:annotation-driven>
HandlerInterceptorAdapter不能攔截WEB-INF目錄以外的jsp文件;若需攔截默認(rèn)index.jsp;可以將index.jsp移動目錄到WEB-INF下即可;
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。