彻底解决springMVC中文乱码

一、页面编码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>

二、URL中的乱码

三、配置过滤器,指定所有请求的编码

  (1)配置spring的编码过滤器,为了防止spring中post方式提交的时候中文乱码,方法:修改web.xml文件,添加spring的编码过滤器


  <filter>
    <filter-name>CharacterEncodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
      <param-name>encodingparam-name>
      <param-value>utf-8param-value>
    init-param>
  filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>
View Code

(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");
        
    }

}
View Code

四、文件编码

  将文件另存为utf-8格式

五、数据库编码

  连接字符串指定编码格式

  

jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=UTF-8

 

转载于:https://www.cnblogs.com/GGYC/p/10638033.html

你可能感兴趣的:(彻底解决springMVC中文乱码)