Spring mvc 拦截器 配置心得

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);
展开阅读全文

没有更多推荐了,返回首页