Spring3 MVC 攔截器
Spring3 MVC 攔截器
我這里定義一個全局的攔截器:
<!-- 攔截器 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/*.do" /> <bean class="com.log.report.interceptor.AccessStatisticsIntceptor" /> </mvc:interceptor> </mvc:interceptors>
定義在servlet-config.xml文件中。
以下是一個攔截器,它用來記錄訪問的ip和流量。
攔截器需要實現HandlerInterceptor接口,同時實現相應的方法。在PreHandler方法中,返回值如果是false,就會攔截住請求。
import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class AccessStatisticsIntceptor implements HandlerInterceptor { public static long access_num = 0; public static Map<String,Long> IPMap = new HashMap<String,Long>(); public static Map<String,Long> urlMap = new HashMap<String,Long>(); @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { // TODO Auto-generated method stub } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { // TODO Auto-generated method stub } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception { access_num += 1; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); Date now = new Date(); String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } String url = request.getRequestURI() != null ? request.getRequestURI().toString() : null; url= sdf.format(now) + "-" + url; if(url != null && urlMap.containsKey(url)) { urlMap.put(url, urlMap.get(url) + 1 ); } else if(url != null) { urlMap.put(url, 1l); } String key = sdf.format(now) + "-" + ip; if(IPMap.containsKey(key)) { IPMap.put(key, IPMap.get(key) + 1 ); } else { IPMap.put(key, 1l); } return true; } }
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!