java web 过滤器 ,对请求的地址(URL)进行过滤。(URL:http: // IP:port / projectname / folder / filename)
即是判断页面是否符合要求,从而是进行放行(正常访问的页面)还是拦截(跳转到设置的错误页面)。
应用之一:用户身份的验证(访问权限)
用法:
设计一个类,实现接口javax.servlet.Filter,并重写方法doFileter,在doFileter中设计过滤条件。若没有接口javax.servlet.Filter,则lib/servlet-api.jar包没有导入工程。
在WEB-INF/ web.xml中配置过滤器。
应用之二:
字符编码的设置。
用法:在doFilter中写语句;request.setCharacterEncoding("UTF-8");
一些示例代码:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>FiveProject</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>loginFilter</filter-name><!--过滤器名字,可以自定义 -->
<filter-class>bao.LoginFilter</filter-class><!--使用该过滤器的类 -->
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/admin/*</url-pattern><!-- 拦截过滤admin文件夹下的所有文件 -->
</filter-mapping>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/view.jsp</url-pattern><!-- 拦截过滤view.jsp文件 -->
</filter-mapping>
<filter>
<filter-name>characterEncoding</filter-name><!-- 过滤器名字,可以自定义 -->
<filter-class>bao.CharacterEncodingFilter</filter-class><!--使用该过滤器的类 -->
</filter>
<filter-mapping>
<filter-name>characterEncoding</filter-name>
<url-pattern>/*</url-pattern><!-- 拦截过滤工程目录下的所有文件 -->
</filter-mapping>
</web-app>