1.编写UserAuthInterceptor必须继承自HandlerInterceptorAdapter
package com.enrol.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class UserAuthInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
//Action之前执行:
System.out.println("--------------UserAuthInterceptor invoke----------------");
String uri = request.getRequestURI();
System.out.println("uri="+uri);
if(uri.indexOf("doLogin") != -1)
{
return true;
}
String username = (String) request.getSession().getAttribute("username");
if(username != null)
{
return true;
}else
{
System.out.println("username == null");
request.getRequestDispatcher("/login.jsp").forward(request, response);
return false;
}
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub
//最后执行,可用于释放资源
System.out.println("--------------UserAuthInterceptor invoke afterCompletion---------------");
super.afterCompletion(request, response, handler, ex);
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
//生成视图之前执行
System.out.println("--------------UserAuthInterceptor invoke postHandle----------------");
// TODO Auto-generated method stub
super.postHandle(request, response, handler, modelAndView);
}
}
2.Spring MVC配置文件中加入以下内容:
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.enrol.interceptor.UserAuthInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
3.web.xml:(放行一些静态文件)
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>