大家好,又见面了,我是你们的朋友全栈君。
package com.demo.test;
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;
public class characterEncodingFilter implements Filter {
private String characterEncoding;
private boolean enabled;
public void destroy() {
// TODO Auto-generated method stub
characterEncoding = null;//销毁时清空资源
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
if(enabled || characterEncoding != null){//如果启用该Filter
request.setCharacterEncoding(characterEncoding);//设置reques编码
response.setCharacterEncoding(characterEncoding);//设置response编码
}
chain.doFilter(request,response );//doFilter,执行下一个Filter或者Servlet
}
public void init(FilterConfig config) throws ServletException {//初始化时加载参数
// TODO Auto-generated method stub
characterEncoding = config.getInitParameter(characterEncoding);//编码方式
enabled = "true".equalsIgnoreCase(config.getInitParameter("enabled").trim());//启用
}
}
characterEncoding表示编码方式,enabled表示是否启用编码,分别从初始化参数中取值。
web.xml中的配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>com.helloweenvsfei.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>characterEncoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>enabled</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
如果使用的字符编码Filter、request中取出的字符可能是乱码,否则不会出乱码。页面编码的方式与Filter编码方式必须一致。另外,如果表单是GET方式提交的,还需要修改Tomcat的conf/servlet.xml配置文件,制定URIEncoding(默认为IOS-8859-1);否则,依然会出现乱码。修改如下:
<Connector port=”8080″ protocol=”HTTP/1.1″ connectionTimeout=”20000″ redirectPort=”8443″ URIEncoding=”UTF-8″>
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/154346.html原文链接:https://javaforall.cn