JAVA实现URL rewrite伪静态,具体代码如下:
urlrewrite伪静态
<rule>
<from><![CDATA[/products/id-([0-9]+)-pid-([0-9]+).html]]></from>
<to><![CDATA[/products/index.jsp?id=$1&pid=$2]]></to>
</rule>
你不是想做java版的伪静态吗 这个比外国的urlrewrite.jar效率更高
JAVA代码:
package org.apple.util.urlrewrite;
/**
*
曹正辉 QQ:330937205 SimpleOnline 开发团队
*
*/
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 开发团队
*
*/
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 开发团队 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所需的配置文件路径出错");
}
} 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) {
// 自动跳转
} else {
filterChain.doFilter(servletRequest, servletResponse);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 每次http访问的时候根据配置文件检查时间大于其系统规定的间隔时间和配置文件是否修改,来决定是否重新加载配置文件
*/
private void reloadConfig() {
/**
* 下面是自动加载配置文件的算法实现
*/
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;
// 修改后重新加载到内存
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 开发团队
*
*/
public class UrlRewriter {
private Rule[] rules;
//构建url匹配规则
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);
}
}
}
//构建url匹配规则
@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 + "值重复");
}
regularExpressionMap.put(from, "ok");
// 加入之前需要检测该from和to所对应的正则表达式是否存在
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();// 只是针对
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);
//如果匹配则进行替换,然后进行页面的跳转
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 开发团队开发的一个UrlRewrite插件--注意该过滤器建议配置为第一个过滤器</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>用于信息调试--该插件自带SimpleOnline 开发团队的日志[log4j]记录插件,建议自己修改源码中的日志记录方式,如果需要修改本团队的日志插件为自身的配置只需修改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"?>
<!--
版权归曹正辉所有 QQ:330937205 SimpleOnline 开发团队[2013-1-1年成立,国内开源开发团队SimpleOnline 欢迎您的加入][负责人曹正辉]
配置如下
<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>
<!-- 插件支持:自动重新加载rule列表 -->
更多信息请查看IT技术专栏