SpringMVC读取Cookie判断用户是否登录,对每一个action都要进行判断。之前使用jstl标签在页面上判断session如果没有登录就使用如下代码跳转到登录页面。
<c:if test="${sessionScope.login == null || sessionScope.login == false}">
<!-- 未登录 -->
<c:redirect url="/login"/>
</c:if>
<c:if test="${sessionScope.login}">
<!-- 已登录 -->
</c:if>
但是测试发现如果session过期,页面渲染就会无故中断并且不会跳转到登录页面。故尝试使用拦截器来进行登录判断。
拦截器配置文件如下
<!-- <mvc:mapping path="/**" /> 如果只写一个*,则不能拦截类似/*/*的请求。静态资源的请求需要判断不进行拦截 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="com.ts.settle.tools.interceptor.LoginInterceptor">
<property name="excludedUrls">
<list>
<value>/login</value>
<value>/static/</value>
</list>
</property>
</bean>
</mvc:interceptor>
</mvc:interceptors>
拦截器实现类如下
public class LoginInterceptor implements HandlerInterceptor {
private AvatarLogger logger = AvatarLoggerFactory.getLogger(this.getClass());
private List<String> excludedUrls;
/**
* 在DispatcherServlet完全处理完请求后被调用
* 当拦截器抛出异常时,依然会从当前拦截器往回执行所的拦截器的afterCompletion()
*/
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception exception)
throws Exception {
}
//在业务处理器处理请求执行完成后,生成视图之前执行的动作
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
}
/**
* 在业务处理器处理请求之前被调用
* 如果返回false 则退出本拦截器,本拦截器后面的postHandle与afterCompletion不再执行
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
String requestUri = request.getRequestURI();
for (String url : excludedUrls) {
if (requestUri.contains(url)) {
return true;
}
}
HttpSession session = request.getSession();
Boolean login = (Boolean) session.getAttribute("login");
if (login == null || !login) {
//System.out.println(request.getContextPath());
logger.info("Pedirect to login page");
response.sendRedirect(request.getContextPath() + "/login");
}
return true;
}
public void setExcludedUrls(List<String> excludedUrls) {
this.excludedUrls = excludedUrls;
}
}