如何在从MySQL(JDBC,JSP)中显示文本时设置UTF-8编码。

huangapple go评论77阅读模式
英文:

How to set UTF-8 encoding when displaying text from MySQL (JDBC,JSP)

问题

我在寻找解决这个编码问题的方法。我尝试了互联网/论坛上找到的几种替代方法,但似乎都没有起作用。

**Connection类**

```java
public class ConnectionFactory {
    public Connection getConnection() {
        try {
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            return DriverManager.getConnection("jdbc:mysql://localhost/fj21?useTimezone=true&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8", "root", "");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

在我的JSP页面中,我使用了以下指令:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

在“my.cnf”文件中,我添加了以下内容:

[client]
default-character-set = utf8mb4

[mysql]
default-character-set = utf8mb4

[mysld]
default-character-set = utf8mb4
collation-server = utf8mb4_unicode_ci 
init-connect = 'SET NAMES utf8mb4'
character-set-server = utf8mb4
character-set-database = utf8mb4

我的MySQL变量如下:

mysql> show variables like '%char%';
+--------------------------+---------------------------------------------------------+
| Variable_name            | Value                                                   |
+--------------------------+---------------------------------------------------------+
| character_set_client     | utf8                                                    |
| character_set_connection | utf8                                                    |
| character_set_database   | utf8mb4                                                 |
| character_set_filesystem | binary                                                  |
| character_set_results    | utf8                                                    |
| character_set_server     | utf8mb4                                                 |
| character_set_system     | utf8                                                    |
| character_sets_dir       | /usr/local/mysql-5.6.34-osx10.11-x86_64/share/charsets/ |
+--------------------------+---------------------------------------------------------+

mysql> show variables like '%coll%';
+----------------------+--------------------+
| Variable_name        | Value              |
+----------------------+--------------------+
| collation_connection | utf8_general_ci    |
| collation_database   | utf8mb4_general_ci |
| collation_server     | utf8mb4_general_ci |
+----------------------+--------------------+

但是记录中仍然没有得到正确的字符(“ç”,“ã”,“á”等):

+----+----------------------+----------------------------+--------------------------------+----------------+
| id | name                 | email                      | address                        | dataNascimento |
+----+----------------------+----------------------------+--------------------------------+----------------+
| 25 | Concei&#195;&#167;&#195;&#163;o          | con@email                  | Rua Concei&#195;&#167;&#195;&#163;o, 1             | 2020-10-04     |
+----+----------------------+----------------------------+--------------------------------+----------------+

我漏掉了什么?...
如何在从MySQL(JDBC,JSP)中显示文本时设置UTF-8编码。



<details>
<summary>英文:</summary>

I&#39;m struggling to find a solution to this encoding problem. I tried several alternatives found on the Internet/forums, but none of them seems to work.

**Connection class**

    public class ConnectionFactory {
	public Connection getConnection() {
		try {
			try {
				Class.forName(&quot;com.mysql.cj.jdbc.Driver&quot;);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			return DriverManager.getConnection(&quot;jdbc:mysql://localhost/fj21?useTimezone=true&amp;serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=utf8&quot;, &quot;root&quot;, &quot;&quot;);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	}

**On my JSP page I&#39;m using the instructions:**

    &lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=UTF-8&quot;
    pageEncoding=&quot;UTF-8&quot;%&gt;

**In &quot;my.cnf&quot; file I added:**

    [client]
    default-character-set = utf8mb4

    [mysql]
    default-character-set = utf8mb4

    [mysld]
    default-character-set = utf8mb4
    collation-server = utf8mb4_unicode_ci 
    init-connect = &#39;SET NAMES utf8mb4&#39;
    character-set-server = utf8mb4
    character-set-database = utf8mb4

**My MySQL variables are:**

    mysql&gt; show variables like &#39;%char%&#39;;
    +--------------------------+---------------------------------------------------------+
    | Variable_name            | Value                                                   |
    +--------------------------+---------------------------------------------------------+
    | character_set_client     | utf8                                                    |
    | character_set_connection | utf8                                                    |
    | character_set_database   | utf8mb4                                                 |
    | character_set_filesystem | binary                                                  |
    | character_set_results    | utf8                                                    |
    | character_set_server     | utf8mb4                                                 |
    | character_set_system     | utf8                                                    |
    | character_sets_dir       | /usr/local/mysql-5.6.34-osx10.11-x86_64/share/charsets/ |
    +--------------------------+---------------------------------------------------------+

    mysql&gt; show variables like &#39;%coll%&#39;;
    +----------------------+--------------------+
    | Variable_name        | Value              |
    +----------------------+--------------------+
    | collation_connection | utf8_general_ci    |
    | collation_database   | utf8mb4_general_ci |
    | collation_server     | utf8mb4_general_ci |
    +----------------------+--------------------+

And I still don&#39;t get the correct characters in the records (&quot;&#231;&quot;, &quot;&#227;&quot;, &quot;&#225;&quot;, etc.):

    +----+----------------------+----------------------------+--------------------------------+----------------+
    | id | name                 | email                      | address                        | dataNascimento |
    +----+----------------------+----------------------------+--------------------------------+----------------+
    | 25 | Concei&#195;&#167;&#195;&#163;o          | con@email                  | Rua Concei&#195;&#167;&#195;&#163;o, 1             | 2020-10-04     |
    +----+----------------------+----------------------------+--------------------------------+----------------

What am I missing?...
:(


</details>


# 答案1
**得分**: 0

尝试将以下过滤器添加到您的项目中:

```java
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter("/*")
public class CharacterEncodingFilter implements Filter {

    @Override
    public void init(FilterConfig config) throws ServletException {
        // NOOP.
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("UTF-8");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        // NOOP.
    }
}

您可能还需要将以下内容添加到您的 web.xml 文件中:

<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>your-class-name</filter-class>
    <init-param>
        <param-name>CharacterEncodingFilter</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
英文:

Try adding this filter to your project:

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter(&quot;/*&quot;)
public class CharacterEncodingFilter implements Filter {

    @Override
    public void init(FilterConfig config) throws ServletException {
        // NOOP.
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding(&quot;UTF-8&quot;);
        filterChain.doFilter(servletRequest, servletResponse);
    }



    @Override
    public void destroy() {
        // NOOP.
    }
}

You may also need to add this to your web.xml file

 &lt;filter&gt;
    &lt;filter-name&gt;CharacterEncodingFilter &lt;/filter-name&gt;
    &lt;filter-class&gt;your-class-name&lt;/filter-class&gt;
      &lt;init-param&gt;
        &lt;param-name&gt;CharacterEncodingFilter &lt;/param-name&gt;
        &lt;param-value&gt;UTF-8&lt;/param-value&gt;
      &lt;/init-param&gt;
  &lt;/filter&gt;

  &lt;filter-mapping&gt;
    &lt;filter-name&gt;CharacterEncodingFilter &lt;/filter-name&gt;
    &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
  &lt;/filter-mapping&gt;

huangapple
  • 本文由 发表于 2020年10月20日 00:37:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/64431648.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定