spring mvc攔截器使用
阿新 • • 發佈:2017-10-26
例子 ttr dir 登錄 sem model imp deb author
舉個例子說下吧,單點登錄,直接看代碼:
spring-mvc.xml配置
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**" /> <mvc:exclude-mapping path="index.html" /> <mvc:exclude-mapping path="/login**" /> <mvc:exclude-mapping path="/register**" /> <mvc:exclude-mapping path="/getVerifyCode**" /> <mvc:exclude-mapping path="/getMethod**" /> <bean class="com.wulinfeng.test.testpilling.util.InterceptorUtil" /> </mvc:interceptor> </mvc:interceptors>
具體攔截器實現類:
import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView; /** * 登陸攔截 * * @author wulinfeng * @version C10 2017年10月11日 * @since SDP V300R003C10 */ public class InterceptorUtil implements HandlerInterceptor { /** 日誌對象 */ private static Logger logger = LogManager.getLogger(InterceptorUtil.class.getName()); /** 是否啟用cookie */ private static final String IS_COOKIE = PropertiesConfigUtil.getProperty("iscookie"); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.debug("InterceptorUtil.doFilter requesturl: " + request.getRequestURL()); String tokenId = null; if (IS_COOKIE.equals("1")) { Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie == null) { continue; } if (cookie.getName().equals("tokenId")) { tokenId = cookie.getValue(); break; } } } } else { if (request.getSession() != null) { tokenId = (String)request.getSession().getAttribute("tokenId"); } } if (StringUtils.isEmpty(tokenId)) { response.sendRedirect("/login.html"); } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // TODO Auto-generated method stub } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // TODO Auto-generated method stub } }
spring mvc攔截器使用