解决中文乱码
解决中文乱码
解决后端响应前端时的中文乱码
package org.example.filter;
import javax.servlet.*;
import java.io.IOException;
public class CharacterEncodingFilter implements Filter {
/**
* 初始化:web服务器启动时就初始化了,等待过滤对象的出现
* @param filterConfig
* @throws ServletException
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("CharacterEncodingFilter初始化了");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
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执行后");
}
/**
* 销毁
*/
@Override
public void destroy() {
System.out.println("CharacterEncodingFilter销毁了");
}
}
web.xml配置
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.example.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<!--只要是 /servlet的任何请求,都会经过这个过滤器-->
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
-------------------------------------------
个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
万水千山总是情,打赏一分行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!