web.xml内容如下:
FirstFilter letian.filter.FirstFilter name1 letian1 name2 letian2 FirstFilter /*
可以看到,过滤器FirstFilter有两个参数name1和name2,值分别是letian1、letian2。
letian/filter/FirstFilter.java内容如下:
package letian.filter;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;public class FirstFilter implements Filter { private String filterName; private String name1; private String name2; public void init(FilterConfig filterConfig) throws ServletException { this.filterName = filterConfig.getFilterName(); this.name1 = filterConfig.getInitParameter("name1"); this.name2 = filterConfig.getInitParameter("name2"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("filterName:"+filterName); System.out.println("name1:"+name1); System.out.println("name2:"+name2); chain.doFilter(request, response); } public void destroy() { }}
letian/servlet/Home.java内容如下:
package letian.servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@WebServlet(name = "Home", urlPatterns = {"/"})public class Home extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("I am home!"); // 输出到控制台 response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { out.println("Hello
"); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }}
效果:
启动tomcat 8后,访问http://localhost:8080/HelloJSP/,可以看到tomcat输出:filterName:FirstFiltername1:letian1name2:letian2I am home!