欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Servlet 3.0 @WebFilter and @WebServlet

程序员文章站 2024-01-11 19:25:58
...

Servlet 3.0 provides new annotation @WebFilter to simplify the configuration of a servlet filter. Here's a simple example and the filter will be invoked with url pattern "/student/*":

 

package com.jxee.action;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;


@WebFilter(urlPatterns="/student/*")
public class TestFilter implements Filter {
  
  private FilterConfig filterConfig;

  @Override
  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) 
      throws IOException, ServletException {
     System.out.println(">>>>>>>>>> start filter");
     String path = ((HttpServletRequest)req).getRequestURI();
     System.out.println(">>>>>>>>>> request URI: " + path);
     chain.doFilter(req, resp);
     System.out.println(">>>>>>>>>> exit filter");
  }

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
     this.filterConfig = filterConfig;
  }
  
  @Override
  public void destroy() {
    System.out.println(">>>>> have a nice one, bye!");
  }
}

 

Servlet 3.0 has similar annotation for servlet. Here's an example, this servlet can be invoked with two url patterns: "/test/myServlet" and "/testServ":

package com.jxee.action;

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(urlPatterns={"/test/myServlet","/testServ"})
public class TestServlet extends HttpServlet {

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp) 
      throws IOException, ServletException {
    System.out.println("------ doGet(req,resp), i c u ------");
    this.doPost(req, resp);
  }
  
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {
    System.out.println("------ doPost(req,resp), i c u ------");
    PrintWriter pw = new PrintWriter(resp.getOutputStream());
    pw.print("i c u!");
    pw.flush();
    pw.close();
  }
}