Java Web中解决乱码的方式
方式一:添加编码过滤器
package com.itmacy.dev.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
/**
* 编码过滤器
* @author itmacy
* @Date 2020/10/21
*/
@WebFilter(urlPatterns = "/*")
public class SetCharacterEncodingFilter implements Filter {
private String newCharset;
public void init(FilterConfig filterConfig) throws ServletException {
if (filterConfig.getInitParameter("newcharset") != null) {
newCharset = filterConfig.getInitParameter("newcharset");
}else {
newCharset = "utf-8";
}
System.out.println("过滤器初始化参数:" + newCharset);
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
req.setCharacterEncoding(newCharset); // 统一请求编码
resp.setContentType("text/html;charset=" + newCharset); // 统一响应编码
filterChain.doFilter(req,resp);
}
public void destroy() {
}
}
方式二:web.xml文件配置编码过滤器
<filter>
<filter-name>SetCharacterEncoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SetCharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>