1.页面编码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
2.URL中的乱码
改tomcat中server.xml中Connector的port=“8080”,加上一个 URIEncoding=”utf-8”
<!-- 配置编码方式过滤器,注意一点:要配置在所有过滤器的前面 -->
<filter>
<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
(2)配置编码过滤器,方法:先创建filter类,再修改web.xml文件,注意的是放在spring的编码过滤器之后
filter类:
package com.qiyuan.filter;
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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class EncoidingFilter implements Filter {
private String encoding="";
@Override
public void destroy() {
// TODO Auto-generated method stub
}
//过滤方法 是否往下执行
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest)arg0;
HttpServletResponse response=(HttpServletResponse)arg1;
request.setCharacterEncoding(encoding);
response.setCharacterEncoding(encoding);
//过滤通行证
chain.doFilter(request, response);
}
//根据web.xml文件的配置进行初始化
@Override
public void init(FilterConfig arg0) throws ServletException {
this.encoding = arg0.getInitParameter("Encoding");
}
}
修改web.xml,添加如下配置:
<!-- 配置编码过滤 --> <filter> <filter-name>EncoidingFilter</filter-name> <filter-class>com.qiyuan.filter.EncoidingFilter</filter-class> <init-param> <param-name>Encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>EncoidingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
4.文件编码
将文件另存为utf-8格式
5.数据库编码
连接字符串指定编码格式
public static String URL="jdbc:mysql://127.0.0.1:3306/mvcdb?useUnicode=true&characterEncoding=UTF-8"
创建数据库的时候指定utf-8编码格式
以上就是动力节点小编告诉大家的彻底解决SpringMVC中文乱码的方法。