public class Filter implements javax.servlet.Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
String age = servletRequest.getParameter("age");
if (Integer.valueOf(age)<80){
//将拦截请求对象和响应对象交还给Tomcat,由Tomcat继续调用资源文件
filterChain.doFilter(servletRequest,servletResponse);//放行
}else {
//过滤器代替Http服务器拒绝本次请求
servletResponse.setContentType("text/html;charset=utf-8");
PrintWriter out = servletResponse.getWriter();
out.print("<center><font style='color:res;font-size:40px'>年龄太大了</font></center>");
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--将过滤器类文件路径给Tomcat-->
<filter>
<filter-name>Filter</filter-name>
<filter-class>com.power.Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>Filter</filter-name>
<url-pattern>/shan.jpg</url-pattern>
</filter-mapping>
</web-app>