JAVA實(shí)現(xiàn)URL rewrite偽靜態(tài)
來源:易賢網(wǎng) 閱讀:1532 次 日期:2015-04-15 14:35:03
溫馨提示:易賢網(wǎng)小編為您整理了“JAVA實(shí)現(xiàn)URL rewrite偽靜態(tài)”,方便廣大網(wǎng)友查閱!

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è)比外國的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年成立,國內(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列表 -->

更多信息請(qǐng)查看IT技術(shù)專欄

更多信息請(qǐng)查看網(wǎng)絡(luò)編程
易賢網(wǎng)手機(jī)網(wǎng)站地址:JAVA實(shí)現(xiàn)URL rewrite偽靜態(tài)
由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢回復(fù)僅供參考,敬請(qǐng)考生以權(quán)威部門公布的正式信息和咨詢?yōu)闇?zhǔn)!

2025國考·省考課程試聽報(bào)名

  • 報(bào)班類型
  • 姓名
  • 手機(jī)號(hào)
  • 驗(yàn)證碼
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡(jiǎn)要咨詢 | 簡(jiǎn)要咨詢須知 | 新媒體/短視頻平臺(tái) | 手機(jī)站點(diǎn) | 投訴建議
工業(yè)和信息化部備案號(hào):滇ICP備2023014141號(hào)-1 云南省教育廳備案號(hào):云教ICP備0901021 滇公網(wǎng)安備53010202001879號(hào) 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號(hào)
云南網(wǎng)警備案專用圖標(biāo)
聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關(guān)注公眾號(hào):hfpxwx
咨詢QQ:1093837350(9:00—18:00)版權(quán)所有:易賢網(wǎng)
云南網(wǎng)警報(bào)警專用圖標(biāo)