通过Web Filter实现一个最简单的UrlRewrite过滤器

工具:支持JavaEE的Eclipse IDE

Web 过滤器可以通过动态Web项目来直接添加;或者直接创建Java项目通过添加类来完成,参看如下过滤器代码:

package me.ereach.urlfilter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebFilter(
	filterName = "Filter01",
	urlPatterns = {"/*"}
)
public class Filter01 implements Filter {
	private FilterConfig fc;
	
	public void init(FilterConfig fConfig) throws ServletException {
		this.fc = fConfig;
	}
	
	public void doFilter(ServletRequest request, 
			ServletResponse response, FilterChain chain) 
			throws IOException, ServletException {
		HttpServletRequest httprequest = (HttpServletRequest)request;
		HttpServletResponse httpresponse = (HttpServletResponse)response;
		
		String contextPath = httprequest.getContextPath();
		String servletPath = httprequest.getServletPath();
		
		if (servletPath.startsWith("/hallo/")) {
			int l = servletPath.length();
			String next = contextPath + servletPath.substring(4);
			
			RequestDispatcher dispatcher = fc.getServletContext().getRequestDispatcher(next);
			dispatcher.forward(request,response);
			
			return;
		}
		else if (servletPath.startsWith("/welcom/hi/")) {
			int l = servletPath.length();
			String next = contextPath + servletPath.substring(9);
			
			RequestDispatcher dispatcher = fc.getServletContext().getRequestDispatcher(next);
			dispatcher.forward(request,response);
			
			return;
		}
		
		chain.doFilter(request, response);
	}
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
}

该过滤器非常简单,所有转发的Url都写在代码里,因此,只要注册了这个过滤器就可以直接使用了。使用这个过滤器还需以下几个步骤:

  1. 导出这个过滤器为一个jar文件。
  2. 把这个jar拷贝到Web App的WEB-INF/lib
  3. 在WEB-INF/web-xml中注册这个jar
  4. 设置context-root为"/"
  5. 重启Web App 

 这个过滤器是针对用户的case来的,够用就好了.

posted @ 2017-09-13 21:17  Jinzd  阅读(345)  评论(0编辑  收藏  举报