spring-mvc.xml
<!-- 以下配置将拦截所有的URL请求 --> <mvc:interceptors> <bean class="**过滤类***AccessHandlerInterceptor" /> </mvc:interceptors> <!-- 以下配置将拦截特有的URL请求 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/main/*"/> <bean class="过滤类" /> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/admin/*.do"/> <bean class="过滤类" /> </mvc:interceptor> </mvc:interceptors> <!-- ps: /**的意思是所有文件夹及里面的子文件夹 /*是所有文件夹,不含子文件夹 -->
java
import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class AccessHandlerInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception { String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; String remoteAddress = request.getRemoteAddr(); String servletPath = request.getServletPath(); String realPath = request.getRealPath("/"); String remoteUser = request.getRemoteUser(); String requestURI = request.getRequestURI(); System.out.println(request.getParameter("path") + "######");// 获取参数 String contextPath = request.getContextPath().replaceAll("\\/+", "/"); String accessUrl = request.getRequestURI().substring( contextPath.length()); //获取需要的信息,不同返回处理 /** response.setStatus(400); response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("<script>window.location.href=\"" + request.getContextPath() + "/error\";</script>"); return false; **/ return true; } @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 } }