标签: 利用 解析 filter | 发表时间:2015-12-26 12:13 | 作者:namezhou
itEye等网站有个很不错的机制,就是每个用户都有一个永久的二级域名 正好所在的项目也想实现这样的功能,研究了一下,发现用过滤器实现最简单,
http://7784.namezhou.com 实际打开的是 http://www.namezhou.com/7784
步骤如下:
1.去DNS供应商开启泛解析,就是加一条cname记录*.namezhou.com 指向www.namezhou.com
2.编写一个Filter,当检测到是二级域名xxx.namezhou.com时,把地址跳转成http://www.namezhou.com/xxx
代码如下:
import java.io.IOException; 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; /** * 泛域名解析过滤器 * @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页面,去嵌入需要显示的页面,但略显山寨
ITeye推荐