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 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
转载本站原创文章,请注明出处,并保留原始链接、图片水印。
本站是一个以用户分享为主的开源技术平台,欢迎各类分享!