Filter servler 的使用

创建filter的类(引用自 T-shirt)
package testfilterservlet;

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;

public class MyFirstFilter implements Filter {

 private FilterConfig config;

 public void init(FilterConfig filterConfig) throws ServletException {
  this.config = filterConfig;
  System.out.println("MyFirstFilter init!");
 }
 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException { 
  String myName = (String)request.getParameter("name");
  if(myName.equals("lsr")){
   System.out.print("lsr");
   chain.doFilter(request,response); //继续响应下一个filter或者servlet
  }else{
   System.out.print("not lsr");
   RequestDispatcher dispatcher = request.getRequestDispatcher("/testForm/testform1.html");
   dispatcher.forward(request,response);
  }
 }
 public void destroy() {
  // TODO 自动生成方法存根
  
  System.out.println("MyFirstFilter destroy!");
 }
}

然后注册(简写)
<web-app>
        <filter>
  <filter-name>MyFirstFilter</filter-name>
  <filter-class>testfilterservlet.MyFirstFilter</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>MyFirstFilter</filter-name>
  <servlet-name>PrintLog</servlet-name> //这里可以使用 url-pattern
 </filter-mapping>

 <servlet>
  <description></description>
  <display-name>PrintLog</display-name>
  <servlet-name>PrintLog</servlet-name>
  <servlet-class>testservlet.PrintLog</servlet-class>
  <init-param>
   <param-name>des</param-name>
   <param-value>this is a test</param-value>
  </init-param>
 </servlet>
 <servlet-mapping>
  <servlet-name>PrintLog</servlet-name>
  <url-pattern>/PrintLog</url-pattern>
 </servlet-mapping>
</web-app>

你可能感兴趣的:(Filter servler 的使用)