您好,登錄后才能下訂單哦!
自定義攔截器類
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;
}
}
//獲取當前的會話session
HttpSession session = request.getSession();
if(session.getAttribute("userid") == null) {
//若登錄session過期或不存在就跳轉到login頁面
request.getRequestDispatcher("/login.jsp").forward(request, response);
return false;
}
return true;
}
}
springmvc-servlet.xml 攔截器注冊
<mvc:interceptors>
<mvc:interceptor>
<!--
/*的意思是所有文件夾及里面的子文件夾
/是所有文件夾,不含子文件夾
/是web項目的根目錄
-->
<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>
<!-- 當設置多個攔截器時,先按順序調用preHandle方法,然后逆序調用每個攔截器的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不處理靜態資源 -->
<mvc:default-servlet-handler />
<!-- 配置注解的處理器映射器和處理器適配器 -->
<mvc:annotation-driven ></mvc:annotation-driven>
HandlerInterceptorAdapter不能攔截WEB-INF目錄以外的jsp文件;若需攔截默認index.jsp;可以將index.jsp移動目錄到WEB-INF下即可;
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。