Spring mvc 攔截器 配置心得
session超過時間自動跳轉到登入頁面。要求請求的每個url都要進行攔截,當然,js,css這些東西除外。
spring-mvc.xml
<!-- 攔截器配置 -->
<mvc:interceptors>
<!-- session逾時 -->
<mvc:interceptor>
<mvc:mapping path="/*/*"/>
<bean class="com.ziyou.platform.interceptor.SessionTimeoutInterceptor">
<property name="allowUrls">
<list>
<!-- 如果請求中包含以下路徑,則不進行攔截 -->
<value>/login</value>
<value>/js</value>
<value>/css</value>
<value>/image</value>
<value>/images</value>
</list>
</property>
</bean>
</mvc:interceptor>
</mvc:interceptors>
<!-- 自定義異常處理,SimpleMappingExceptionResolver這個類可以是個空類,但是要寫,友善在java代碼裡面使用 -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.ziyou.platform.interceptor.SessionTimeoutException">redirect:/login</prop>
</props>
</property>
</bean>
/**
* 處理session逾時的攔截器
*/
public class SessionTimeoutInterceptor implements HandlerInterceptor{
public String[] allowUrls;//還沒發現可以直接配置不攔截的資源,是以在代碼裡面來排除
public void setAllowUrls(String[] allowUrls) {
this.allowUrls = allowUrls;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object arg2) throws Exception {
String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");
System.out.println(requestUrl);
if(null != allowUrls && allowUrls.length>=1)
for(String url : allowUrls) {
if(requestUrl.contains(url)) {
return true;
}
}
User user = (User) request.getSession().getAttribute("user");
if(user != null) {
return true; //傳回true,則這個方面調用後會接着調用postHandle(), afterCompletion()
}else{
// 未登入 跳轉到登入頁面
throw new SessionTimeoutException();//傳回到配置檔案中定義的路徑
}
}
@Override
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
}
}
另外,你要在controller中設定session的逾時時間
request.getSession().setMaxInactiveInterval(20);//20秒
request.getSession().setAttribute("user", user);