二级域名通过urlRewrite实现

/ java / 没有评论 / 3270浏览

最近业务扩展,新业务需要二级域名,查了一些资料和目前业务上的框架,得出来思路:

目前项目里已经有个url过滤器了,用的是微软提供的jar,但不支持二级域名。要么去改jar里的源码,要么再写一个过滤器。

为了降低风险,重写了一个过滤器,作用全局。过滤器作用大致如下:

  1. 原域名的请求,直接放过,让其继续走原来的urlRewrite过滤器
  2. 二级域名下的ajax请求,这些请求属于一级域名的,故直接放过
  3. 二级域名下的链接请请求,走新的过滤器,并且通过forward方式跳转

有些人问二级域名下的ajax请求如何放过?

答:这需要在一个.xml里配置相关正则,在配置文件里匹配不到请求,就可放行让其执行老的过滤器

下面是具体代码

/**
 * 二级域名过滤器
 * 不同业务的二级域名命名约束:例子:secondDomainUrlrewrite-licai.xml,secondDomainUrlrewrite-baike.xml
 * 取licai为key,secondDomainUrlrewrite-licai.xml文件里的url为集合,存储到domain2Patter
 * @author Administrator
 *
 */
public class SecondDomainFilter implements Filter {
    private Logger                logger        = Logger.getLogger(SecondDomainFilter.class);
 
    Map<String, List<URLMapping>> domain2Patter = new HashMap<String, List<URLMapping>>();
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //         TODO Auto-generated method stub
        String configPath = filterConfig.getInitParameter("confPath");
        String[] configPaths = configPath.split(",");
        for (String p : configPaths) {//例子:/WEB-INF/classes/secondDomainUrlrewrite-licai.xml
            String realPath = filterConfig.getServletContext().getRealPath(p);
            String fileName = new File(realPath).getName();
            String yuSecondDomain = fileName.split("\\.")[0].split("-")[1];
            FileInputStream input = null;
            byte buff[] = null;
            List<URLMapping> urlPatternList = null;
            try {
                input = new FileInputStream(realPath);
                buff = new byte[input.available()];
                input.read(buff);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block  
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block  
                e.printStackTrace();
            } finally {
                try {
                    input.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            /** 
             * 通过开源XStream来解析XML,并转化成Java对象 
             */
            XStream xstream = new XStream(new DomDriver());
            xstream.alias("rule", URLMapping.class);
            xstream.alias("urlrewrite", ArrayList.class);
            urlPatternList = (List) xstream.fromXML(new String(buff));
            domain2Patter.put(yuSecondDomain, urlPatternList);
        }
    }
 
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                                                                                             throws IOException,
                                                                                             ServletException {
        // TODO Auto-generated method stub
        HttpServletRequest req = (HttpServletRequest) request;
        String serverName = req.getServerName();
        if (!checkIfSecondDomain(serverName)) {//非二级域名直接过滤掉,走原来的filter
            chain.doFilter(req, response);
            return;
        }
        Map<String, Object> map = getRealURI(serverName, req.getRequestURI());
        if ((boolean) map.get("secondDomain")) {
            req.getRequestDispatcher((String) map.get("realUri")).forward(req, response);
            return;
        }
        //非二级域名下的ajax继续走下一个过滤器
        chain.doFilter(req, response);
    }
 
    //检验是否为项目中定义的二级域名
    private boolean checkIfSecondDomain(String serverName) {
        if (StringUtils.isBlank(serverName))
            return false;
        if (SystemUtil.getSystemProperty("IW_SITE_URL_http").equals(serverName)
            || serverName.contains(SystemUtil.getSystemProperty("IW_SITE_URL"))
            || SystemUtil.getSystemProperty("IW_SITE_URL_http").contains(serverName))
            return false;
        String secondDomain = null;
        if (serverName.contains("."))
            secondDomain = serverName.substring(0, serverName.indexOf("."));
        if (StringUtils.isBlank(secondDomain))
            return false;
        for (SecondDomainEnum sdomain : SecondDomainEnum.values()) {
            if (sdomain == null)
                continue;
            if (secondDomain.equals(sdomain.getSecondDomain()))
                return true;
        }
        return false;
    }
 
    //通过uri获取服务器真正的url action
    private Map<String, Object> getRealURI(String serverName, String requestURI) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("secondDomain", false);
        String secondDomain = serverName.substring(0, serverName.indexOf("."));
        if (StringUtils.isBlank(secondDomain))
            return map;
        try {
            List<URLMapping> urlPatterns = domain2Patter.get(secondDomain);
            if (CollectionUtils.isNotEmpty(urlPatterns)) {
                for (URLMapping url : urlPatterns) {
                    Pattern pattern = Pattern.compile(url.getFrom());
                    Matcher matcher = pattern.matcher(requestURI);
                    if (matcher.find()) {
                        String reqPara = url.getTo();
                        for (int i = 1; i < matcher.groupCount(); i++) {
                            reqPara = reqPara.replace("$" + i, matcher.group(i));
                        }
                        map.put("secondDomain", true);
                        map.put("realUri", reqPara);
                        return map;
                    }
                }
            }
        } catch (Exception e) {
            logger.warn("url regex error," + "requestURI:" + requestURI);
        }
        return map;
    }
 
    @Override
    public void destroy() {
        // TODO Auto-generated method stub
 
    }
 
    static class URLMapping {
 
        String from;
        String to;
 
        public String getFrom() {
            return from;
        }
 
        public void setFrom(String from) {
            this.from = from;
        }
 
        public String getTo() {
            return to;
        }
 
        public void setTo(String to) {
            this.to = to;
        }
 
    }
 
}

web.xml配置示例如下:

<filter>
        <filter-name>SecondDomainFilter</filter-name>
        <filter-class>
            com.manyi.iw.userconsole.filter.SecondDomainFilter
        </filter-class>
        <init-param>
            <param-name>confPath</param-name>
            <param-value>/WEB-INF/classes/secondDomainUrlrewrite-licai.xml</param-value>
        </init-param>
</filter>

<filter-mapping>
		<filter-name>SecondDomainFilter</filter-name>
		<url-pattern>/*</url-pattern>
</filter-mapping>

重定向.xml配置文件示例如下:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 3.2//EN"
        "http://tuckey.org/res/dtds/urlrewrite3.2.dtd">
<urlrewrite use-query-string="true">
 
	
	<rule>
		<from>^/abc/bb/([0-9a-zA-Z_-]{11})/(\?.+)?$</from>
		<to>/licai.action?code=$1</to>
	</rule>
	
	
</urlrewrite>