通过Filter实现二级域名和URLRewrite

需求1.1:

一级域名: http://www.iteye.com/

二级域名: http://firefly.iteye.com/

这里firefly其实会Mapping到用户ID,根据用户ID来展示不用用户的Blog,javaeye是通过Ruby实现的, 那Java如何实现这个Mapping呢?

 

需求1.2:

我们查看具体的哪一篇文章是通过 http://firefly.iteye.com/blog/785171 来访问的,这个URL是如何传参数的呢?

 

思路2:

A. 通过过滤器获得二级域名.(eg. firefly)

B. 对URL进行重写Rewrite.

 

实现3:

3.1 创建一个URLFilter过滤器,对所有的请求进行过滤

package com.firefly.web;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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 com.firefly.web.URLRewriter.URLMapping;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * Servlet Filter implementation class URLFilter
 */
public class URLFilter implements Filter {

	List <URLMapping>urlPatternList;
	
    public URLFilter() {
        // TODO Auto-generated constructor stub
    }

    /**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {		
		
		/**
		 * 初始化
		 */
		String configPath=fConfig.getInitParameter("configPath");		
		String realConfigPath=fConfig.getServletContext().getRealPath(configPath);		
		FileInputStream input;
		byte buff[]=null;
		try {
			input = new FileInputStream(realConfigPath);
			buff=new byte[input.available()];			
			input.read(buff);
			input.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		/**
		 * 通过开源XStream来解析XML,并转化成Java对象
		 */
		XStream xstream = new XStream(new DomDriver()); 
		xstream.alias("url", URLMapping.class);
		xstream.alias("URLList", ArrayList.class);		
		urlPatternList=(List)xstream.fromXML(new String(buff));
	}
	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
				
		HttpServletRequest httpServletRequest = (HttpServletRequest) request; 
		/**
		 * 获得服务器名称,如:firefly.iteye.com/
		 */
		String serverName=request.getServerName();
		int endIndex=serverName.indexOf(".");
		/**
		 * 获得二级域名
		 * 二级域名一般是一个ID, 如:firefly
		 */
		String secondDomainName=serverName.substring(0, endIndex);	
		request.setAttribute("userID", secondDomainName);
		if(secondDomainName.equalsIgnoreCase("www")){
			httpServletRequest.getRequestDispatcher( "/index.html")   
            .forward(request, response);  
			return;
			
		}else{
			String realPath=this.getRealPath(httpServletRequest.getRequestURI());			
			httpServletRequest.getRequestDispatcher("/"+realPath)   
            .forward(request, response);  
			return;
		}		
	}
	
	/**
	 * 将URI转换成真正的请求URL
	 * e.g firefly.iteye.com/blog/785171 -> 
	 *     firefly.iteye.com/dispatcher.do?action=displayBlog&blogId=785171
	 * @param URI
	 * @return
	 */
	private String getRealPath(String URI){		
		for(URLMapping url:urlPatternList){
			Pattern pattern=Pattern.compile(url.getPattern());
			Matcher matcher=pattern.matcher(URI);
			if(matcher.find()){ 
				String reqPara=url.getReqParameter();
				for(int i=1;i<=matcher.groupCount();i++){
					reqPara=reqPara.replace("${"+i+"}", matcher.group(i));
				}
				return reqPara;
				
			}				
		}
		return URI;
		
	}
	

}

  

 3.2 创建URLMapping类

package com.firefly.web.URLRewriter;

public class URLMapping {

	String pattern;
	String reqParameter;
	public String getPattern() {
		return pattern;
	}
	public void setPattern(String pattern) {
		this.pattern = pattern;
	}
	public String getReqParameter() {
		return reqParameter;
	}
	public void setReqParameter(String reqParameter) {
		this.reqParameter = reqParameter;
	}	
	
}

 

 

3.3 在Web.xml中配置过滤器,对所有请求都进行处理

 

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<display-name>parseDomain</display-name>
	<filter>
		<description>
		</description>
		<display-name>URLFilter</display-name>
		<filter-name>URLFilter</filter-name>		
		<filter-class>com.firefly.web.URLFilter</filter-class>
		<init-param>
			<param-name>configPath</param-name>
			<param-value>/WEB-INF/URLRewriter.xml</param-value>
		</init-param>		
	</filter>
	<filter-mapping>
		<filter-name>URLFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>	
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>	
	</welcome-file-list>
</web-app>

 

3.4 在/WEB-INF下创建URLRewriter.xml

 

<?xml version="1.0" encoding="utf-8" ?> 
<URLList>	
	<url>
		<pattern>/order/(\d*)/(\d*)</pattern>
		<reqParameter>dispatcher.do?action=order&amp;productId=${1}&amp;number=${2}</reqParameter>
	</url>
	<url>
		<pattern>/blog/(\d*)</pattern>
		<reqParameter>dispatcher.do?action=displayBlog&amp;blogId=${1}</reqParameter>
	</url>
</URLList>

 

附言: 如果要在本地测试二级域名,需要在hosts文件中配置如下参数(C:\WINDOWS\system32\drivers\etc\hosts)

127.0.0.1      firefly.iteye.com

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值