zoukankan      html  css  js  c++  java
  • ssm项目中中文字符乱码

      昨天给同学改一个错,在SSM项目中,表单输入的String类型中,中文字符值,总是乱码,在控制器层获取的数据就开始乱码,先后进行了如下排查:

    • web.xml中配置设置字符编码的监听器(过滤器),
    • jsp页面的编码格式,用记事本打开查看,
    • 对jsp页面中设置编码格式

    排查完之后,都没有问题,还是乱码,然后她今天早上来问老师.老师给了解决方法.

    在控制器层得到字符串数据后,对字符串进行加工,将字符串转化为字节数组,然后以指定的编码方式在编码为字符串.

     1 package com.qst.util;
     2 
     3 /**
     4  * @Description : 字符串转换编码格式为utf-8
     5  * @Author: Liruilong
     6  * @Date: 2019/9/29 10:38
     7  */
     8 public class Util_UTF8 {
     9 
    10     // String(byte[] bytes, Charset charset) 通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String。
    11     //getBytes(Charset charset)   使用给定的 charset 将此 String 编码到 byte 序列,并将结果存储到新的 byte 数组。
    12 
    13     public static String toUTF8(String str) {
    14         try {
    15             // 如果编码格式为GB2313,则转换为UTF-8
    16             if (str.equals(new String(str.getBytes("GB2312"), "GB2312"))) {
    17                 str = new String(str.getBytes("GB2312"), "utf-8");
    18                 return str;
    19             }
    20         } catch (Exception exception) {
    21         }
    22         try {
    23             // 如果编码格式为"西欧字符集"转化为utf-8
    24             if (str.equals(new String(str.getBytes("ISO-8859-1"), "ISO-8859-1"))) {
    25                 str = new String(str.getBytes("ISO-8859-1"), "utf-8");
    26                 return str;
    27             }
    28         } catch (Exception exception1) {
    29         }
    30         try {
    31             // 如果编码格式为GBK,转换为utf-8.
    32             if (str.equals(new String(str.getBytes("GBK"), "GBK"))) {
    33                 str = new String(str.getBytes("GBK"), "utf-8");
    34                 return str;
    35             }
    36         } catch (Exception exception3) {
    37         }
    38         return str;
    39     }
    40 }

    加油生活 ^_^   2019.9.29 

  • 相关阅读:
    异常介绍
    docker 命令
    acm
    Openfiler能把标准x86/64架构的系统变成一个强大的NAS、SAN存储和IP存储网关
    docker 图解学习
    基于Docker的TensorFlow机器学习框架搭建和实例源码解读
    菜鸟打印控件
    Oracle 12c on Solaris 10 安装文档
    内存对齐小解
    安装oracle 11gr2 rac on solaris
  • 原文地址:https://www.cnblogs.com/liruilong/p/11606840.html
Copyright © 2011-2022 走看看