Java connection utf 8

Как заставить UTF-8 работать в веб-приложениях Java?

Пользователи в основном используют Firefox2, но для доступа к сайту используются Opera 9.x, FF3, IE7 и Google Chrome.

12 ответов

Отвечая на вопрос, как часто задаваемые вопросы этого сайта поощряют его. Это работает для меня:

В основном символы äåö не являются проблематичными, поскольку набор символов по умолчанию, используемый браузерами, и tomcat/java для webapps — latin1, т.е. ISO-8859-1, который «понимает» эти символы.

Чтобы получить UTF-8, работающий под Java + Tomcat + Linux/Windows + Mysql, требуется следующее:

Настройка Tomcat server.xml

Необходимо настроить, чтобы соединитель использовал UTF-8 для кодирования параметров URL-адреса (GET-запроса):

Ключевой частью является URIEncoding = «UTF-8» в приведенном выше примере. Это гарантирует, что Tomcat обрабатывает все входящие параметры GET как кодированные UTF-8. В результате, когда пользователь записывает следующее в адресную строку браузера:

 https://localhost:8443/ID/Users?action=search&name=*ж* 

символ ж обрабатывается как UTF-8 и кодируется (как правило, браузером, даже до получения доступа к серверу) как % D0% B6.

Запрос POST не влияет на это.

CharsetFilter

Затем настало время заставить java webapp обрабатывать все запросы и ответы как кодированные UTF-8. Это требует, чтобы мы определили фильтр набора символов, как показано ниже:

package fi.foo.filters; import javax.servlet.*; import java.io.IOException; public class CharsetFilter implements Filter < private String encoding; public void init(FilterConfig config) throws ServletException < encoding = config.getInitParameter("requestEncoding"); if (encoding == null) encoding = "UTF-8"; >public void doFilter(ServletRequest request, ServletResponse response, FilterChain next) throws IOException, ServletException < // Respect the client-specified character encoding // (see HTTP specification section 3.4.1) if (null == request.getCharacterEncoding()) < request.setCharacterEncoding(encoding); >// Set the default response content type and encoding response.setContentType("text/html; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); next.doFilter(request, response); > public void destroy() < >> 

Этот фильтр гарантирует, что если браузер не установил кодировку, используемую в запросе, она настроена на UTF-8.

Другое, что делает этот фильтр, — это установить кодировку ответа по умолчанию, т.е. кодирование, в котором возвращен html/whatever. Альтернативой является установка кодировки ответа и т.д. В каждом контроллере приложения.

Этот фильтр необходимо добавить в web.xml или дескриптор развертывания webapp:

   CharsetFilter fi.foo.filters.CharsetFilter requestEncoding UTF-8   CharsetFilter /*  

Копирование страницы JSP

В web.xml добавьте следующее:

В качестве альтернативы, все JSP-страницы webapp должны иметь следующее в верхней части:

Если используется какой-то макет с различными JSP-фрагментами, то это необходимо в all из них.

HTML-метатеги

Кодирование страницы JSP сообщает JVM обрабатывать символы на странице JSP в правильной кодировке. Затем настало время сообщить vrowser, в котором кодировка html-страницы:

Читайте также:  max-height

Это делается с помощью следующего в верхней части каждой xhtml-страницы, созданной webapp:

JDBC-соединение

При использовании db необходимо определить, что соединение использует кодировку UTF-8. Это делается в context.xml или везде, где соединение JDBC определяется следующим образом:

База данных MySQL и таблицы

Используемая база данных должна использовать кодировку UTF-8. Это достигается путем создания базы данных со следующим:

 CREATE DATABASE `ID_development` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_swedish_ci */; 

Затем все таблицы должны быть в UTF-8 также:

 CREATE TABLE `Users` ( `id` int(10) unsigned NOT NULL auto_increment, `name` varchar(30) collate utf8_swedish_ci default NULL PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci ROW_FORMAT=DYNAMIC; 

Ключевой частью является CHARSET = utf8.

Конфигурация сервера MySQL

Необходимо также настроить MySQL serveri. Обычно это делается в Windows путем изменения my.ini -file и в Linux путем настройки my.cnf -file. В этих файлах должно быть определено, что все клиенты, подключенные к серверу, используют utf8 в качестве набора символов по умолчанию и что кодировка по умолчанию, используемая сервером, также является utf8.

 [client] port=3306 default-character-set=utf8 [mysql] default-character-set=utf8 

Процедуры и функции Mysql

Они также должны иметь определенный набор символов. Например:

 DELIMITER $$ DROP FUNCTION IF EXISTS `pathToNode` $$ CREATE FUNCTION `pathToNode` (ryhma_id INT) RETURNS TEXT CHARACTER SET utf8 READS SQL DATA BEGIN DECLARE path VARCHAR(255) CHARACTER SET utf8; SET path = NULL; . RETURN path; END $$ DELIMITER ; 

Запросы GET: latin1 и UTF-8

Если и когда он определен в tomcat server.xml, параметры запроса GET закодированы в UTF-8, обрабатываются следующие запросы GET:

 https://localhost:8443/ID/Users?action=search&name=Petteri https://localhost:8443/ID/Users?action=search&name=ж 

Поскольку символы ASCII кодируются одинаково с латинскими и UTF-8, строка «Petteri» обрабатывается правильно.

Кириллический символ ж вообще не понимается в латинском языке1. Поскольку Tomcat получил указание обрабатывать параметры запроса как UTF-8, он правильно кодирует этот символ как % D0% B6.

Если и когда браузеру предлагается читать страницы в кодировке UTF-8 (с заголовками запросов и метатегами html), по крайней мере Firefox 2/3 и другие браузеры с этого периода кодируют сам символ как % D0% B6.

Конечным результатом является поиск всех пользователей с именем «Petteri», а также все пользователи с именем «ж».

Но как насчет äåö?

HTTP-спецификация определяет, что по умолчанию URL-адреса кодируются как latin1. Это приводит к тому, что firefox2, firefox3 и т.д. Кодируют следующие

 https://localhost:8443/ID/Users?action=search&name=*Päivi* 
 https://localhost:8443/ID/Users?action=search&name=*P%E4ivi* 

В латинском языке символ ä кодируется как % E4. Несмотря на то, что страница/запрос/все определено для использования UTF-8. Закодированная версия UTF-8 ä имеет значение % C3% A4

Результатом этого является то, что webapp не может корректно обрабатывать параметры запроса из запросов GET, поскольку некоторые символы кодируются в latin1 и другие в UTF-8. Примечание: запросы POST работают, поскольку браузеры кодируют все параметры запроса из форм полностью в UTF-8, если страница определена как UTF-8

Материал для чтения

Очень большое спасибо за авторов следующих за ответы на мои проблемы:

  • http://tagunov.tripod.com/i18n/i18n.html
  • http://wiki.apache.org/tomcat/Tomcat/UTF-8
  • http://java.sun.com/developer/technicalArticles/Intl/HTTPCharset/
  • http://dev.mysql.com/doc/refman/5.0/ru/charset-syntax.html
  • http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-tomcat-jsp-etc.html
  • http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-for-mysql-tomcat.html
  • http://jeppesn.dk/utf-8.html
  • http://www.nabble.com/request-parameters-mishandle-utf-8-encoding-td18720039.html
  • http://www.utoronto.ca/webdocs/HTMLdocs/NewHTML/iso_table.html
  • http://www.utf8-chartable.de/
Читайте также:  .

Важное примечание

mysql поддерживает Базовая многоязычная плоскость с использованием 3-байтных символов UTF-8. Если вам нужно выйти за пределы этого (для некоторых алфавитов требуется более 3 байтов UTF-8), вам нужно либо использовать атрибут типа столбца VARBINARY , либо использовать utf8mb4 набор символов (для чего требуется MySQL 5.5.3 или новее). Просто имейте в виду, что использование набора символов utf8 в MySQL не будет работать в течение 100% времени.

Tomcat с Apache

Еще одна вещь. Если вы используете соединитель Apache + Tomcat + mod_JK, вам также необходимо выполнить следующие изменения:

  • Добавить URIEncoding = «UTF-8» в файл tomcat server.xml для коннектора 8009, он используется коннектором mod_JK.
  • Перейдите в папку apache i.e /etc/httpd/conf и добавьте AddDefaultCharset utf-8 в httpd.conf file . Примечание.. Сначала убедитесь, что он существует или нет. Если существует, вы можете обновить его с помощью этой строки. Вы также можете добавить эту строку внизу.

Источник

Java connection utf 8

All strings sent from the JDBC driver to the server are converted automatically from native Java Unicode form to the connection’s character encoding, including all queries sent using Statement.execute() , Statement.executeUpdate() , and Statement.executeQuery() , as well as all PreparedStatement and CallableStatement parameters, excluding parameters set using the following methods:

  • setBlob()
  • setBytes()
  • setClob()
  • setNClob()
  • setAsciiStream()
  • setBinaryStream()
  • setCharacterStream()
  • setNCharacterStream()
  • setUnicodeStream()

Number of Encodings Per Connection

Connector/J supports a single character encoding between the client and the server, and any number of character encodings for data returned by the server to the client in ResultSets .

Setting the Character Encoding

For Connector/J 8.0.25 and earlier: The character encoding between the client and the server is automatically detected upon connection (provided that the Connector/J connection properties characterEncoding and connectionCollation are not set). The encoding on the server is specified using the system variable character_set_server (for more information, see Server Character Set and Collation), and the driver automatically uses the encoding. For example, to use the 4-byte UTF-8 character set with Connector/J, configure the MySQL server with character_set_server=utf8mb4 , and leave characterEncoding and connectionCollation out of the Connector/J connection string. Connector/J will then autodetect the UTF-8 setting. To override the automatically detected encoding on the client side, use the characterEncoding property in the connection URL to the server.

For Connector/J 8.0.26 and later: There are two phases during the connection initialization in which the character encoding and collation are set.

  • Pre-Authentication Phase: In this phase, the character encoding between the client and the server is determined by the settings of the Connector/J connection properties, in the following order of priority:
  • passwordCharacterEncoding
  • connectionCollation
  • characterEncoding
  • Set to UTF8 (corresponds to utf8mb4 on MySQL servers), if none of the properties above is set
Читайте также:  Java interface with static class

Post-Authentication Phase : In this phase, the character encoding between the client and the server for the rest of the session is determined by the settings of the Connector/J connection properties, in the following order of priority:

  • connectionCollation
  • characterEncoding
  • Set to UTF8 (corresponds to utf8mb4 on MySQL servers), if none of the properties above is set

This means Connector/J needs to issue a SET NAMES Statement to change the character set and collation that were established in the pre-authentication phase only if passwordCharacterEncoding is set, but its setting is different from that of connectionCollation , or different from that of characterEncoding (when connectionCollation is not set), or different from utf8mb4 (when both connectionCollation and characterEncoding are not set).

Custom Character Sets and Collations

For Connector/J 8.0.26 and later only: To support the use of custom character sets and collations on the server, set the Connector/J connection property detectCustomCollations to true , and provide the mapping between the custom character sets and the Java character encodings by supplying the customCharsetMapping connection property with a comma-delimited list of custom_charset : java_encoding pairs (for example: customCharsetMapping=charset1:UTF-8,charset2:Cp1252 ).

MySQL to Java Encoding Name Translations

Use Java-style names when specifying character encodings. The following table lists MySQL character set names and their corresponding Java-style names:

Table 6.21 MySQL to Java Encoding Name Translations

For 8.0.12 and earlier : utf8

For 8.0.13 and later : utf8mb4

For Connector/J 8.0.12 and earlier: In order to use the utf8mb4 character set for the connection, the server MUST be configured with character_set_server=utf8mb4 ; if that is not the case, when UTF-8 is used for characterEncoding in the connection string, it will map to the MySQL character set name utf8 , which is an alias for utf8mb3 .

For Connector/J 8.0.13 and later:

  • When UTF-8 is used for characterEncoding in the connection string, it maps to the MySQL character set name utf8mb4 .
  • If the connection option connectionCollation is also set alongside characterEncoding and is incompatible with it, characterEncoding will be overridden with the encoding corresponding to connectionCollation .
  • Because there is no Java-style character set name for utfmb3 that you can use with the connection option charaterEncoding , the only way to use utf8mb3 as your connection character set is to use a utf8mb3 collation (for example, utf8_general_ci ) for the connection option connectionCollation , which forces a utf8mb3 character set to be used, as explained in the last bullet.

Do not issue the query SET NAMES with Connector/J, as the driver will not detect that the character set has been changed by the query, and will continue to use the character set configured when the connection was first set up.

Источник

Оцените статью