彻底解决springMVC中文乱码
一、页面编码
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
二、URL中的乱码
改tomcat中server.xml中Connector的port=“8080”,加上一个 URIEncoding=”utf-8”
三、配置过滤器,指定所有请求的编码
(1)配置spring的编码过滤器,为了防止spring中post方式提交的时候中文乱码,方法:修改web.xml文件,添加spring的编码过滤器
<!-- 配置编码方式过滤器,注意一点:要配置在所有过滤器的前面 --> <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>
四、文件编码
将文件另存为utf-8格式
五、数据库编码
连接字符串指定编码格式
public static String URL="jdbc:mysql://127.0.0.1:3306/mvcdb?useUnicode=true&characterEncoding=UTF-8"
创建数据库的时候指定utf-8编码格式
六、其他参考资料
http://www.cnblogs.com/javahr/p/8268983.html