七.乱码问题
1.使用过滤器 (之前做web项目弄过,直接贴代码
package com.why;
import javax.servlet.*;
import java.io.IOException;
/**
* @program: Spring_MVC
* @description:
* @author: @why
* @create: 2020-08-19 15:40
**/
public class EncodeFilter 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");
filterChain.doFilter(servletRequest,servletResponse);
servletResponse.setCharacterEncoding("utf-8");
}
@Override
public void destroy() {
}
}
web.xml的配置
<filter>
<filter-name>encoding</filter-name>
<filter-class>com.why.EncodeFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.使用spring带的拦截器
<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>
<url-pattern>/*</url-pattern>
</filter-mapping>
3.注意 /和/*
-
< url-pattern>/</url-pattern>
-
会匹配到/login这样的路径型url,不会匹配到模式为*.jsp这样的后缀型url
-
< url-pattern>/</url-pattern>
-
会匹配所有url:路径型的和后缀型的url(包括/login,.jsp,.js和*.html等)