码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-09-13 22:12:00      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:设置   ext   java web   response   ted   contex   log   override   import   

工具:支持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以使设置生效 

 

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

标签:设置   ext   java web   response   ted   contex   log   override   import   

原文地址:http://www.cnblogs.com/jinzd/p/7517765.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!