利用泛解析和Filter實現動態二級域名

itEye等網站有個很不錯的機制,就是每一個用戶都有一個永久的二級域名 正好所在的項目也想實現這樣的功能,研究了一下,發現用過濾器實現最簡單,java

http://7784.namezhou.com 實際打開的是 http://www.namezhou.com/7784app

步驟以下:dom

1.去DNS供應商開啓泛解析,就是加一條cname記錄*.namezhou.com 指向www.namezhou.comide

2.編寫一個Filter,當檢測到是二級域名xxx.namezhou.com時,把地址跳轉成http://www.namezhou.com/xxx網站

代碼以下:this

import java.io.IOException;url

import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;.net

/**code

  • 泛域名解析過濾器get

  • @author namezhou

  • @since Dec 26, 2015 */ public class DomainFilter implements Filter{ private String mainDomain;//主域名裸域地址 private String expectDomain;//排除域名,分號隔開 public String getMainDomain() { return mainDomain; } public void setMainDomain(String mainDomain) { this.mainDomain = mainDomain; } public String getExpectDomain() { return expectDomain; } public void setExpectDomain(String expectDomain) { this.expectDomain = expectDomain; } @Override public void destroy() {

    } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String url = ((HttpServletRequest)request).getRequestURI(); String host = request.getServerName(); boolean redirect = false; if(host.equals(mainDomain)){ //訪問的裸域 chain.doFilter(request, response); }else if(expectDomain!=null&&expectDomain.trim().length()>0){ String[] arr = expectDomain.split(";"); if(arr!=null&&arr.length>0){ for (int i = 0; i < arr.length; i++) { if(host.equals(arr[i]+"."+mainDomain)){ //排除的域,直接顯示 redirect = true; chain.doFilter(request, response); } } } } if(!redirect){ //檢查是否是有 String id = host.replace("."+mainDomain, ""); ((HttpServletResponse)response).sendRedirect("http://www.namezhou.com/"+id); } } @Override public void init(FilterConfig arg0) throws ServletException { expectDomain = arg0.getInitParameter("expectDomain"); mainDomain = arg0.getInitParameter("mainDomain"); } } 3.配置該Filter

<!-- 泛域名解析過濾器 start -->

<filter>
	<filter-name>domainFilter</filter-name>
	<filter-class>com.namezhou.common.filter.DomainFilter</filter-class>
	<init-param>
		<param-name>mainDomain</param-name>
		<param-value>namezhou.com</param-value>
	</init-param>
	<init-param>
		<param-name>expectDomain</param-name>
		<param-value>www;dev</param-value>
	</init-param>
</filter>
<filter-mapping>
	<filter-name>domainFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 泛域名解析過濾器 end -->

博客裏面還有另一種基於Apache rewrite模塊的實現方法,與那種方法比較起來,過濾器實現方式

優勢:簡單,邏輯清晰,實現方便,

缺點:訪問地址會變,固然也能夠弄一個空iframe頁面,去嵌入須要顯示的頁面,但略顯山寨

相關文章
相關標籤/搜索