【日常积累】web乱码一锅炖

乱码常见场景:页面显示乱码,表单提交乱码,数据库存储乱码等。

乱码原因:编码-解码过程中码表不一致产生的。

字符编码:页面默认编码为ISO-8859-1,简体中文编码为GB2312(2个字节),中文汉字集(简体与繁体)编码为GBK(2个字节),国际编码为UTF-8(3个字节)。

显示乱码:
    HTML中<head>标签下:<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    JSP中顶部添加:<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
        <head>标签下添加:<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    IDE中设置jsp页面编码utf-8:以eclipse为例,window > Prefrences > Web > JSP    Files > Encoding处改成支持UTF-8格式的选项。
    
传输乱码:
    tomcat中 servlet.xml 中配置:
        <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000"
               redirectPort="8443" URIEncoding="UTF-8"/>
    
    request请求:
            浏览器使用什么码表打开当前页面, 就使用什么码表来发送请求参数.
        get请求Java代码手动编解码:username= new String(username.getBytes("ISO-8859-1"),"UTF-8");
        post请求:request.setCharacterEncoding("utf-8");
    
    response响应:
        response.setCharacterEncoding("utf-8"); //通知服务器使用utf-8来发送响应实体中数据
        response.getOutputStream().write("中国".getBytes("utf-8"));// 指定编码为utf-8 -- 只对本行有效
        
        response.setContentType("text/html;charset=utf-8");//指定浏览器在接收数据时也使用同一个编码来打开数据
        response.setHeader("Content-Type", "text/html;charset=utf-8");//与上面等价
        
    Filter 过滤器:
        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>
            <init-param>
                <param-name>forceEncoding</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>

        <filter-mapping>
            <filter-name>characterEncodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        
    数据库连接:
        MySQL: url="jdbc:mysql://localhost:3306/Laptop?useUnicode=true&characterEncoding=utf-8"
        MySQL修改默认客户端连接字符集:修改配置文件my.ini编码  default-character-set=utf-8。
        
    插入数据库
        建库;CREATE DATABASE mydb3 CHARACTER SET utf8 COLLATE utf8_bin;
        建表:CREATE TABLE `books` (
                              ......
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;


参考:https://blog.csdn.net/u010246789/article/details/52669998
           https://blog.csdn.net/GreetTuring/article/details/55682565
           https://www.cnblogs.com/cst11021/p/4964007.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值