SpringMVC的拦截器(Interceptor)和Servlet的过滤器(Filter)有着近乎相同的功能,推荐登录使用Filter去做登录的拦截(个人比较喜欢Filter过滤的范围,要比Interceptor大很多)。
好了,首先写SpringMVC的拦截器,我们要写一个类,并且这个类实现HandlerInterceptor接口(也可以继承HandlerInterceptorAdapter类):
/**
*
*/
package com.zjoa.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
*
* @author DuZhuo
* 登录拦截器
*/
@Repository
public class SystemInitInterceptor implements HandlerInterceptor {
@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 {
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object arg2) throws Exception {
//获取url地址
String reqUrl=request.getRequestURI().replace(request.getContextPath(), "");
//当url地址为登录的url的时候跳过拦截器
if(reqUrl.contains("/login.htm")){
return true;
}else{
HttpSession session=request.getSession();
Object obj=session.getAttribute("user");
if(obj==null||"".equals(obj.toString())){
response.sendRedirect("error.jsp");
}
}
return true;
}
}
然后我们去配置SpringMVC的xml文件:
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.zjoa"/>
<!--设置登录拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/*.htm" />
<mvc:mapping path="/*/*.htm" />
<bean class="com.zjoa.interceptor.SystemInitInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
</beans>