仿一个urlrewrite 支持二级域名

因为urlrewrite 不支持二级域名 也懒得改了 直接写一个:

适用场景同一个站点多个二级域名,写的很粗糙 如下:

UrlWriter

public class UrlWriter {
    private String from;
    private String to;
    private String type;

    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;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}
UrlWriterFactory

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class UrlWriterFactory {
    private Log logger = LogFactory.getLog(UrlWriterFactory.class);

    private static final String FORWARD = "forward";

    private static final String REDIRECT = "redirect";

    private static final String DEFAULT_CONFIG_FILE_NAME = "urlrewrite.xml";

    private static String urlWriterConfigName;

    /**
     * 版本号
     */
    private Long version = System.currentTimeMillis();

    private static List<UrlWriter> urlPatternList = new ArrayList<UrlWriter>();

    public void init() {
        if (StringUtils.isBlank(urlWriterConfigName)) {
            urlWriterConfigName = DEFAULT_CONFIG_FILE_NAME;
        }
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(urlWriterConfigName);
        if (null == inputStream) {
            throw new RuntimeException("没有配置urlrewrite.xml");
        }
        urlPatternList = initUrlWriter(inputStream);
    }

    @SuppressWarnings("unchecked")
    private List<UrlWriter> initUrlWriter(InputStream inputStream) {
        List<UrlWriter> urlPatternList = new ArrayList<UrlWriter>();
        SAXReader reader = new SAXReader();
        try {
            Document doc = reader.read(inputStream);
            List<Element> nodes = doc.selectNodes("urlrewrite/rule");

            for (Element elm : nodes) {
                UrlWriter urlMapping = new UrlWriter();
                String from = elm.elementText("from");
                from = StringUtils.isBlank(from) ? "" : from;
                urlMapping.setFrom(from);

                String to = elm.elementText("to");
                to = StringUtils.isBlank(to) ? "" : to;
                urlMapping.setTo(to);

                Attribute attribute = elm.element("to").attribute("type");
                String type = FORWARD;
                if (null != attribute) {
                    if (StringUtils.isBlank(attribute.getValue())) {
                        type = attribute.getValue();
                    }
                }
                urlMapping.setType(type);
                urlPatternList.add(urlMapping);
            }
            return urlPatternList;
        } catch (DocumentException e) {

            logger.error("解析url.xml时发现异常:" + e);
        }
        return urlPatternList;

    }

    public static UrlResult getUrlResult(String url) {
        if (StringUtils.isEmpty(url)) {
            return null;
        }
        url = filterUrlStyle(url);
        UrlResult urlResult = new UrlResult(false, "");
        for (UrlWriter urlMapping : urlPatternList) {
            Pattern pattern = Pattern.compile(urlMapping.getFrom());
            Matcher matcher = pattern.matcher(url);
            if (matcher.find()) {
                urlResult.setUrl(matcher.replaceAll(urlMapping.getTo()));
                if (urlMapping.getType().equals(REDIRECT)) {
                    urlResult.setFlag(true);
                }
                return urlResult;
            }
        }
        return urlResult;
    }

    public static class UrlResult {
        private boolean flag = false;
        private String url = "";

        public UrlResult(boolean flag, String url) {
            super();
            this.flag = flag;
            this.url = url;
        }

        public boolean isFlag() {
            return flag;
        }

        public void setFlag(boolean flag) {
            this.flag = flag;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }
    }

    public String getUrlWriterConfigName() {
        return urlWriterConfigName;
    }

    public void setUrlWriterConfigName(String urlWriterConfigName) {
        UrlWriterFactory.urlWriterConfigName = urlWriterConfigName;
    }

    public Long getVersion() {
        return version;
    }

    public void setVersion(Long version) {
        this.version = version;
    }


    private static String filterUrlStyle(String url) {
        if (url.indexOf("://") != -1) {
            url = url.substring(url.indexOf("://") + 3);
        }
        if (url.length() > 1 && url.endsWith("/")) {
            url = url.substring(0, url.length() - 1);
        }
        return url;
    }

}
UrlWriterFilter

public class UrlWriterFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String requestURL = httpServletRequest.getRequestURL().toString();
        UrlResult urlResult = UrlWriterFactory.getUrlResult(requestURL);
        if (null != urlResult && StringUtils.isNotBlank(urlResult.getUrl())) {
            String realPath = urlResult.getUrl();
            if (urlResult.isFlag()) {
                httpServletResponse.sendRedirect(realPath);
                return;
            } else {
                if (!realPath.startsWith("/")) {
                    realPath = "/" + realPath;
                }
                httpServletRequest.getRequestDispatcher(realPath).forward(request, response);
                return;
            }
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

}
urlrewrite.xml

<?xml version="1.0" encoding="utf-8"?>
<urlrewrite>

    <rule>
        <from>^(aa|bb|cc|dd|ee|ff|gg).oschina.net$</from>
        <to type="forward">/industry?dns=$1</to>
    </rule>
   
</urlrewrite>
web.xml

<filter>
        <filter-name>UrlWriterFilter</filter-name>
        <filter-class>com.test.commons.uri.UrlWriterFilter</filter-class>
    </filter>

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

你可能感兴趣的:(仿一个urlrewrite 支持二级域名)