二级域名通过urlRewrite实现

为应对新业务对二级域名的需求,本文介绍了如何在已有的URL过滤器基础上,通过编写新的过滤器来实现二级域名的支持。主要内容包括:1) 对原域名请求保持不变;2) 允许二级域名下的AJAX请求;3) 对二级域名链接进行新过滤器处理,使用forward方式跳转。配置关键在于正确匹配和过滤请求。

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

目前项目里已经有个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>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值