JAVA實(shí)現(xiàn)URL rewrite偽靜態(tài)

字號(hào):


    JAVA實(shí)現(xiàn)URL rewrite偽靜態(tài),具體代碼如下:
    urlrewrite偽靜態(tài)
    <rule>
    <from><![CDATA[/products/id-([0-9]+)-pid-([0-9]+).html]]></from>
    <to><![CDATA[/products/index.jsp?id=$1&pid=$2]]></to>
    </rule>
    你不是想做java版的偽靜態(tài)嗎 這個(gè)比外國(guó)的urlrewrite.jar效率更高
    JAVA代碼:
    package org.apple.util.urlrewrite;
    /**
    *
    曹正輝 QQ:330937205 SimpleOnline 開發(fā)團(tuán)隊(duì)
    *
    */
    public class Rule {
    @Override
    public String toString() {
    return "Rule [from=" + from + ", to=" + to + "]";
    }
    private String from;
    private String to;
    public void setFrom(String from) {
    this.from = from;
    }
    public String getFrom() {
    return from;
    }
    public void setTo(String to) {
    this.to = to;
    }
    public String getTo() {
    return to;
    }
    /**
    * 真正的處理方法
    *
    */
    public String dealWithUrl(String url, Boolean isHandler) {
    boolean isMatches = url.matches(from);
    if (isMatches) {
    isHandler = true;
    url = url.replaceAll(from, to);
    return url;
    } else {
    return url;
    }
    }
    }
    package org.apple.util.urlrewrite;
    /**
    *
    曹正輝 QQ:330937205 SimpleOnline 開發(fā)團(tuán)隊(duì)
    *
    */
    public class StringUtils {
    public static boolean isBlank(String string) {
    if (string == null) {
    return true;
    } else {
    return false;
    }
    }
    public static boolean isNotBlank(String string) {
    if (string != null && "".equals(string.trim())) {
    return true;
    } else {
    return false;
    }
    }
    }
    package org.apple.util.urlrewrite;
    import java.io.File;
    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;
    /**
    *
    曹正輝 QQ:330937205 SimpleOnline 開發(fā)團(tuán)隊(duì) 2013-9-2
    *
    */
    public class UrlRewriteFilter implements Filter {
    private UrlRewriter urlRewriter;
    private boolean reloadConfig = true;
    private long reloadConfigInterval = 60;
    private String configPath = "/WEB-INF/urlrewrite.xml";
    private String configURLPath = "";
    private long lastReloadConfigCheckTime = System.currentTimeMillis();
    private long configFilelastModified = System.currentTimeMillis();
    public void init(FilterConfig filterConfig) throws ServletException {
    String configPath = filterConfig.getInitParameter("configPath");
    if (StringUtils.isNotBlank(configPath)) {
    this.configURLPath = WebPath.WebRootPath + configPath;
    File file = new File(this.configURLPath);
    if (!file.exists()) {
    throw new RuntimeException("urlrewrite所需的配置文件路徑出錯(cuò)");
    }
    } else {
    this.configURLPath = WebPath.WebRootPath + this.configPath;
    File file = new File(this.configURLPath);
    if (!file.exists()) {
    throw new RuntimeException("urlrewrite.xml配置文件不存在");
    }
    }
    urlRewriter = new UrlRewriter(configURLPath);
    }
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    if (this.reloadConfig) {
    reloadConfig();
    }
    try {
    boolean isOk = urlRewriter.dealWithUrl((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse);
    if (isOk) {
    // 自動(dòng)跳轉(zhuǎn)
    } else {
    filterChain.doFilter(servletRequest, servletResponse);
    }
    } catch (Exception e) {
    throw new RuntimeException(e);
    }
    }
    /**
    * 每次http訪問的時(shí)候根據(jù)配置文件檢查時(shí)間大于其系統(tǒng)規(guī)定的間隔時(shí)間和配置文件是否修改,來決定是否重新加載配置文件
    */
    private void reloadConfig() {
    /**
    * 下面是自動(dòng)加載配置文件的算法實(shí)現(xiàn)
    */
    long now = System.currentTimeMillis();
    if ((now - this.reloadConfigInterval > this.lastReloadConfigCheckTime)) {
    this.lastReloadConfigCheckTime = now;
    File file = new File(this.configURLPath);
    long lastModified = file.lastModified();
    if (configFilelastModified != lastModified) {
    configFilelastModified = lastModified;
    // 修改后重新加載到內(nèi)存
    urlRewriter = new UrlRewriter(configURLPath);
    }
    }
    }
    public void destroy() {
    }
    }
    package org.apple.util.urlrewrite;
    import java.io.File;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.dom4j.Document;
    import org.dom4j.Element;
    import org.dom4j.io.SAXReader;
    /**
    *
    曹正輝 QQ:330937205 SimpleOnline 開發(fā)團(tuán)隊(duì)
    *
    */
    public class UrlRewriter {
    private Rule[] rules;
    //構(gòu)建url匹配規(guī)則
    public UrlRewriter(String configURLPath) {
    ArrayList<Rule> roleUrlList = getAllRileList(configURLPath);
    int size = roleUrlList.size();
    rules = new Rule[size];
    if (size != 0) {
    for (int i = 0; i < size; i++) {
    rules[i] = roleUrlList.get(i);
    }
    }
    }
    //構(gòu)建url匹配規(guī)則
    @SuppressWarnings("unchecked")
    public ArrayList<Rule> getAllRileList(String filePath) {
    Map<String, String> regularExpressionMap = new HashMap<String, String>();
    ArrayList<Rule> roleUrlList = null;
    try {
    SAXReader reader = new SAXReader();
    Document document = reader.read(new File(filePath));
    Element root = document.getRootElement();
    roleUrlList = new ArrayList<Rule>();
    for (Iterator<Rule> iterator = root.elementIterator(); iterator.hasNext();) {
    Element element = (Element) iterator.next();
    Rule rule = new Rule();
    rule.setFrom(element.elementText("from"));
    rule.setTo(element.elementText("to"));
    String from = element.elementText("from");
    if (regularExpressionMap.containsKey(from)) {
    throw new RuntimeException("from: " + from + "值重復(fù)");
    }
    regularExpressionMap.put(from, "ok");
    // 加入之前需要檢測(cè)該from和to所對(duì)應(yīng)的正則表達(dá)式是否存在
    roleUrlList.add(rule);
    }
    } catch (Exception e) {
    throw new RuntimeException(e);
    }
    return roleUrlList;
    }
    public boolean dealWithUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String url = request.getServletPath().trim();// 只是針對(duì)
    String url_copy = url;
    if (rules.length != 0) {
    int rulesLength = rules.length;
    Boolean isHandler = false;
    for (int i = 0; i < rulesLength; i++) {
    url = rules[i].dealWithUrl(url, isHandler);
    //如果匹配則進(jìn)行替換,然后進(jìn)行頁面的跳轉(zhuǎn)
    if (url != null && !"".equals(url) && (!url_copy.equals(url))) {
    request.getRequestDispatcher(url).forward(request, response);
    return true;
    }
    }
    }
    return false;
    }
    }
    package org.apple.util.urlrewrite;
    public class WebPath {//獲取web根目錄
    /**
    * @return eg:/D:/apache-tomcat-6.0.35/webapps/urlrewrite/
    */
    public static String WebRootPath = WebPath.class.getResource("/").getPath().toString().replace("/WEB-INF/classes/", "");
    }
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="
    xmlns:xsi=""
    xsi:schemaLocation=
    ">
    <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <filter>
    <display-name>SimpleOnline 開發(fā)團(tuán)隊(duì)開發(fā)的一個(gè)UrlRewrite插件--注意該過濾器建議配置為第一個(gè)過濾器</display-name>
    <filter-name>UrlRewriteFilter</filter-name>
    <filter-class>org.apple.util.urlrewrite.UrlRewriteFilter</filter-class>
    <init-param>
    <param-name>configPath</param-name>
    <param-value>/WEB-INF/urlrewrite.xml</param-value>
    </init-param>
    <init-param>
    <description>用于信息調(diào)試--該插件自帶SimpleOnline 開發(fā)團(tuán)隊(duì)的日志[log4j]記錄插件,建議自己修改源碼中的日志記錄方式,如果需要修改本團(tuán)隊(duì)的日志插件為自身的配置只需修改Apple-CommonsLogging.jar/log4j.properties中的配置</description>
    <param-name>devMode</param-name>
    <param-value>true</param-value>
    </init-param>
    </filter>
    <filter-mapping>
    <filter-name>UrlRewriteFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
    </web-app>
    <?xml version="1.0" encoding="utf-8"?>
    <!--
    版權(quán)歸曹正輝所有 QQ:330937205 SimpleOnline 開發(fā)團(tuán)隊(duì)[2013-1-1年成立,國(guó)內(nèi)開源開發(fā)團(tuán)隊(duì)SimpleOnline 歡迎您的加入][負(fù)責(zé)人曹正輝]
    配置如下
    <filter>
    <filter-name>UrlRewriteFilter</filter-name>
    <filter-class>org.apple.util.urlrewrite.UrlRewriteFilter</filter-class>
    <init-param>
    <param-name>configPath</param-name>
    <param-value>/WEB-INF/urlrewrite.xml</param-value>
    </init-param>
    <init-param>
    <param-name>devMode</param-name>
    <param-value>true</param-value>
    </init-param>
    </filter>
    <filter-mapping>
    <filter-name>UrlRewriteFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
    下面是支持的策略
    注意<from><![CDATA[/test]]></from>
    <to><![CDATA[/rewrite.jsp]]></to>中間不要有空格
    -->
    <urlrewrite>
    <rule>
    <from><![CDATA[/test]]></from>
    <to><![CDATA[/rewrite.jsp]]></to>
    </rule>
    <rule>
    <from><![CDATA[/test/test]]></from>
    <to><![CDATA[/rewrite.jsp]]></to>
    </rule>
    <rule>
    <from><![CDATA[/some/old/page.html]]></from>
    <to><![CDATA[/some/new/page.html]]></to>
    </rule>
    <rule>
    <from><![CDATA[/test/test/(.*)]]></from>
    <to><![CDATA[/test2/test2/$1]]></to>
    </rule>
    <rule>
    <from><![CDATA[/products/([0-9]+)]]></from>
    <to><![CDATA[/products/index.jsp?id=$1]]></to>
    </rule>
    <rule>
    <from><![CDATA[/products/([0-9]+)/([0-9]+)]]></from>
    <to><![CDATA[/products/index.jsp?id=$1&pid=$2]]></to>
    </rule>
    </urlrewrite>
    <!-- 插件支持:自動(dòng)重新加載rule列表 -->