Spring Boot 多个域名指向同一IP
一、需求:直接通过域名访问首页(同一应用下,多个首页,包括PC端、手机端首页)
方法:采用多个域名绑定同一IP下同一应用,不同域名对应不同产品(PC、手机端)的方法,在后台通过拦截器判断 request 中的host字段值,进而重定向到不同的页面
@Configuration @EnableWebMvc public class InterceptorConfig extends WebMvcConfigurerAdapter { @Bean public HostInterceptor hostInterceptor() { return new HostInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(hostInterceptor()).addPathPatterns("/"); super.addInterceptors(registry); } }
package com.zxguan.thymeleaf.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author zxguan * @description * @create 2018-03-16 10:28 */ public class HostInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String host = request.getHeader("host"); if (host.equals("localhost")) { response.sendRedirect("/home"); } else { response.sendRedirect("/index"); } return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
@RequestMapping(value = {"/", "/index"}) public String test() { return "test"; } @RequestMapping(value = "/home") public String home() { return "home"; }