接到这样一个需求:现有项目X,在我方的服务器A和客户的服务器B上均有部署。用户之前都是访问的A,现在要求所有用户的请求都转发到服务器B上去。考虑到用户可能保存了很多不同的网址(不止是主页网址),现写一个拦截器,把指向A服务器IP的请求都转发到B上去。代码如下:
拦截器代码:
package com.yiji.ifp.web.common.interceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @Description 使所有的請求都跳轉到指定頁面 * @Author Created by shusheng. * @Email shusheng@xxx.com * @Date 2017/10/31 */ public class HostRedirectInterceptor extends HandlerInterceptorAdapter { protected final Logger logger = LoggerFactory.getLogger(getClass()); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String hostFromRequest = request.getLocalAddr(); logger.info("用戶請求的主機地址:{}", hostFromRequest); String requestURL = request.getRequestURI(); logger.info("客户端发出请求时的完整URL:{}",requestURL); String requestURI = request.getRequestURI(); logger.info("请求行中的资源名部分:{}",requestURI); String hostTo = "http://59.51.9.109:8081/"; String urlTo = "/ifp/common/redirectionwindow.html"; if(!(requestURL.equals(urlTo)||"/".equals(requestURL))){ logger.info("用戶請求的服務器地址不是新地址,将转发请求到服务器跳转页"); response.sendRedirect(urlTo); logger.info("重定向完成"); return false; } return true; } }
配置代码:
<mvc:interceptors>
<bean id="hostRedirectInterceptor" class="com.xxx.xxx.web.common.interceptor.HostRedirectInterceptor" />
</mvc:interceptors>