springMVC——拦截器的实现登录控制
拦截器配置文件如下
<!-- <mvc:mapping path="/**" /> 如果只写一个*,则不能拦截类似/*/*的请求。静态资源的请求需要判断不进行拦截 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="包名.LoginInterceptor">
<property name="excludedUrls">
<list>
<value>/login</value>
<value>/static/</value>
</list>
</property>
</bean>
</mvc:interceptor>
</mvc:interceptors>
java代码:
public class HandlerInterceptor1 extends HandlerInterceptorAdapter {
private AvatarLogger logger = AvatarLoggerFactory.getLogger(this.getClass());
private List<String> excludedUrls;
/**
* 在业务处理器处理请求之前被调用
* 如果返回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;
}
}