编码设置过滤的注意点 2021-04-27
作者:互联网
特别要注意 / 和/*的区别
首先用Spring里面自带的编码过滤器(CharacterEncodingFilter)吧,也可以自己写过滤器,反正就是把所有的乱码都设置成UTF-8
<!--SpringMvc解决乱码配置-->
<filter>
<filter-name>encoding</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>encoding</filter-name>
<!--过滤所有的请求 / :不包括jsp的页面,而且=展示的页面正好在jsp页面中,filter相当于根本没派上用场 要写/* -->
<url-pattern>/*</url-pattern>
</filter-mapping>
当然也是可以自己写过滤器啦,在web.xml中自己配置好文件的位置.
<!--过滤器解决乱码 一般固定写进xml文件-->
<filter>
<filter-name>encoding</filter-name>
<filter-class>cn.com.zzn.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<!--过滤所有的请求 / :不包括jsp的页面,而且=展示的页面正好在jsp页面中,filter相当于根本没派上用场 要写/* -->
<url-pattern>/*</url-pattern>
</filter-mapping>
写过滤器文件和实现类
重点注意这句话: filterChain.doFilter(servletRequest,servletResponse);
Filter若不写chain.doFilter(request,response)原Servlet路径代码不会被执行
package cn.com.zzn.filter;
import javax.servlet.*;
import java.io.IOException;
public class EncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
标签:27,04,encoding,doFilter,2021,servletResponse,过滤器,servletRequest,public 来源: https://blog.csdn.net/weixin_49092494/article/details/116210736