【问题标题】:Encoding problem in POST method Spring and ThymeleafPOST方法Spring和Thymeleaf中的编码问题
【发布时间】:2021-07-28 17:36:30
【问题描述】:

我做了一个简单的表格,用户输入一个名字,然后这个名字被存储在数据库中。我正在使用Spring MVCThymeleaf。我的数据库是MySQL。当我尝试输入非拉丁字符时出现问题。

在数据库中存储非拉丁语name 后,我尝试在网页上显示它,但我得到的不是西里尔字符,而是这样的奇怪字符:

Ð〜ѼÑ

  • 我确信数据库中的编码是正确的,因为当我尝试 使用MySQL Workbench 存储一个非拉丁名称,编码是 对。
  • Thymeleaf 编码也设置为 UTF-8。当我放时,非翻译字符正确显示 例如,在这样的标签中:

<h1> Заголовок </h1>

我已经试过了:

  • 在 html 文件中添加这一行:<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
  • form 标签中添加此属性:<form accept-charset="UTF-8" ...

但是没有任何效果。我做错了什么?

【问题讨论】:

  • 您是否尝试在 url 数据源中指定字符集? spring.datasource.url = jdbc:mysql://localhost:3306/YOUR_DB_NAME?useUnicode=yes&characterEncoding=UTF-8
  • 我试过了,但没有任何改变
  • 我之前试过了。添加此配置后,GET 请求开始使用非拉丁字符正常工作。不幸的是,它不适用于 POST
  • 在数据库中的所有表和文本列上指定 utf8mb4 字符集。更多UTF-8 all the way through。您正面临一个简单的mojibake 案例,例如 Python 'Имя'.encode('utf-8').decode('cp1252','ignore')(返回 'ИмÑ')。

标签: java spring forms encoding thymeleaf


【解决方案1】:

我找了很多,终于找到了解决办法。

- 我宁愿将第一个称为解决方法而不是解决方案:

    @PostMapping
    public String create(@RequestParam("name") String name, @RequestParam("age") int age) {      

        byte[] bytes = name.getBytes(StandardCharsets.ISO_8859_1);
        name = new String(bytes, StandardCharsets.UTF_8); // now "name" contains characters in the correct encoding

        ...
    }

- 在我看来,第二种解决方案看起来要好得多:
首先,创建一个Filter 类并在那里设置POST请求的编码:

   public class RequestFilter extends HttpFilter {
        @Override
        protected void doFilter(HttpServletRequest request, HttpServletResponse response,
                                FilterChain chain) throws IOException, ServletException
        {
            request.setCharacterEncoding("UTF-8");
            chain.doFilter(request, response);
        }
    }

那么你应该在web.xml注册一个Filter

 <filter>
    <filter-name>filter_nane</filter-name>
    <filter-class>class_path_to_filter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>filter_nane</filter-name>
    <url-pattern>/*</url-pattern> 
  </filter-mapping>

【讨论】:

    【解决方案2】:

    我遇到了类似的问题。谢谢你的回答@gurmigou。您为我指明了前进的方向,我找到了更好的解决方案。

        <filter>
        <filter-name>filter</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>filter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
    

    【讨论】:

      猜你喜欢
      • 2019-10-02
      • 2013-12-16
      • 2017-08-10
      • 2016-01-08
      • 2016-01-11
      • 2019-03-25
      • 1970-01-01
      • 2011-02-01
      • 1970-01-01
      相关资源
      最近更新 更多