工具:支持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都写在代码里,因此,只要注册了这个过滤器就可以直接使用了。使用这个过滤器还需以下几个步骤:
- 导出这个过滤器为一个jar文件。
- 把这个jar拷贝到Web App的WEB-INF/lib
- 在WEB-INF/web-xml中注册这个jar
- 设置context-root为"/"
- 重启Web App以使设置生效
时间: 2024-10-13 02:19:29