拦截器实现对用户是否登录及登陆超时的验证
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 以下配置将拦截所有的URL请求 -->
<mvc:interceptors>
<bean />
</mvc:interceptors>
<!-- 以下配置将拦截特有的URL请求 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/secure/*"/>
<bean />
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/admin/*.do"/>
<bean />
</mvc:interceptor>
</mvc:interceptors>
</beans>
定义的拦截器只需要实现@Override
public boolean preHandle(HttpServletRequest req,HttpServletResponse res, Object handler)
?
举一个实际的例子进行说明:
?
1、spring-mvc.xml配置文件中
<!-- 用户登录校验 -->
??? <mvc:interceptors>
??? ??? <bean };??? //url中如果有login和handle不拦截
??????? String uri = request.getRequestURI();
?
??????? if (uri.indexOf("common") != -1) {?
??????????? boolean beFilter = true;?
??????????? for (String s : noFilters) {?
??????????????? if (uri.indexOf(s) != -1) {?
??????????????????? beFilter = false;?
??????????????????? break;?
??????????????? }
??????????? }?
??????????? if (beFilter) {?
??????????????? Object obj = request.getSession().getAttribute(SystemConstants.LOGINED);?
??????????????? if (null == obj) {?
??????????????????? // 未登录?
??????????????? ??? PrintWriter out = response.getWriter();?
??????????????????? StringBuilder builder = new StringBuilder();?
??????????????????? builder.append("<script type="text/javascript" charset="UTF-8">");?
??????????????????? builder.append("alert("页面过期,请重新登录");");?
??????????????????? builder.append("window.top.location.href="");?
??????????????????? builder.append(SystemConstants.BASEPATH);? //这里是http://ip:port/项目名
??????????????????? builder.append("/common/user/login";</script>");? //这里是重新登录的页面url
??????????????????? out.print(builder.toString());?
??????????????????? out.close();?
??????????????????? return false;?
??????????????? }
??????????? }?
??????? }?
??????? return super.preHandle(request, response, handler);?
??? }?
??? ?
??? /**
??? ?* 生成视图之前执行
??? ?*/
??? @Override?
??? public void postHandle(HttpServletRequest request,?
??? ??????? HttpServletResponse response, Object handler,?
??? ??????? ModelAndView modelAndView) throws Exception {?
??? }?
??? ?
??? /**
??? ?* 最后执行,可用于释放资源
??? ?*/
??? @Override?
??? public void afterCompletion(HttpServletRequest request,?
??? ??????? HttpServletResponse response, Object handler, Exception ex)?
??? ??????? throws Exception {?
??? }?
}
?
3、配置session的有效期
在web.xml中添加
<session-config>
? <session-timeout>30</session-timeout>
?</session-config>
在30分钟之内session有效,在测试的时候可以讲其改为1,一分钟之后再访问,就会弹出提示“重新登录”的窗口