Filter:过滤器,用来过滤网站的数据
-
处理中文乱码
-
登录验证....
也就是说,web传进来的数据要经过这个接口Filter,把一些不想要的东西帮你过滤掉。
1、在pom.xml中配置依赖
<dependencies>
<!-- servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!-- JSP依赖-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
<!-- JSTL表达式的依赖-->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<!-- standard标签库的依赖-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- 连接数据库的依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
2、创建filter过滤器,重写里面的方法即可(实现Filter接口中不要导错包)
package com.lyh.filter;
import javax.servlet.*;
import java.io.IOException;
public class CharacterEncodingFilter implements Filter {
// 初始化:web服务刚启动,就会被初始化
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("CharacterEncoding初始化");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//filterChain:过滤器的链
/*
1.过滤器中的所以代码,在过滤器特定请求的时候都会被执行
2.必须要让过滤器继续同行filterChain.doFilter(servletRequest,servletResponse);
*/
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charset=utf-8");
System.out.println("CharacterEncodingFilter执行前");
//请我们的请求继续走,如果不写,程序到这就会被拦截
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("CharacterEncodingFilter执行后");
}
// 销毁:当Web服务器关闭是,会销毁过滤器
@Override
public void destroy() {
System.out.println("CharacterEncoding销毁");
}
}
3、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">
<servlet>
<servlet-name>show</servlet-name>
<servlet-class>com.lyh.servlet.ShowServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>show</servlet-name>
<url-pattern>/servlet/show</url-pattern>
</servlet-mapping>
<!-- 当/servlet/*路径下的所以运行的服务器都会被过滤-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.lyh.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
</web-app>
标签:十一,Filter,servletResponse,过滤器,servlet,javax,CharacterEncodingFilter
From: https://www.cnblogs.com/lyhidea/p/16950465.html