springmvc拦截器的配置、使用:
自定义拦截器,实现HandlerInterceptor接口。
配置mvc.xml
<mvc:interceptors>
<!-- 使用bean定义一个Interceptor,直接定义在mvc:interceptors根下面的Interceptor将拦截所有的请求 -->
<mvc:interceptor>
<!-- 进行拦截:/**表示拦截所有controller -->
<mvc:mapping path="/login/**" />
<bean class="com.gcsoft.web.login.Login" />
</mvc:interceptor>
</mvc:interceptors>
java:
package com.gcsoft.web.login;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import cn.gcsoft.cons.CommonConstant;
import cn.gcsoft.model.User;
public class Login implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest httpRequest, HttpServletResponse httpResponse, 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 object) throws Exception {
String urlString = request.getRequestURI();
String contextPath = request.getContextPath();
User user = (User) request.getSession().getAttribute(CommonConstant.USER_CONTEXT);
if (!urlString.endsWith("doLogin.action")) {
if (user == null) {
response.sendRedirect(contextPath + "/login/doLogin.action");
return true;
}
}
return true;
}
}