创建ForwardServlet,用于请求转发
public class ForwardServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/MyServlet").forward(request,
response);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
创建过滤器ForwardFilter
public class ForwardFilter implements Filter {
public void init(FilterConfig fConfig) throws ServletException {
// 过滤器对象在初始化时调用,可以配置一些初始化参数
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// 用于拦截用户的请求,如果和当前过滤器的拦截路径匹配,该方法会被调用
PrintWriter out=response.getWriter();
out.write("Hello FilterTest");
}
public void destroy() {
// 过滤器对象在销毁时自动调用,释放资源
}
}
配置过滤器拦截请求 /MyServlet
@WebFilter(filterName = "ForwardFilter",urlPatterns = "/MyServlet")
启动tomcat,请求ForwardServlet
http://localhost:8080/chapter08/ForwardServlet
浏览器输出:Hello MyServlet
说明ForwardFilter没有拦截到ForwardServlet请求转发的请求(/MyServlet)。
增加配置,拦截请求转发
@WebFilter(filterName = "ForwardFilter",urlPatterns = "/MyServlet",dispatcherTypes = DispatcherType.FORWARD)
重新启动tomcat,请求ForwardServlet,浏览器输出:Hello FilterTest