Solve the problem of springmvc+mybatis+mysql Chinese scrambled code

  • 2020-04-01 04:08:53
  • OfStack

Recently, I used ajax to request springmvc to query mysql database in the background

The initial configuration in mybatis is as follows


<select id="queryContentById" resultType = "java.lang.String" parameterType="String" >
    select text from News where id=#{o} 
</select>

The text field of the table News is of type blob

The resulting text value is always garbled in the console.

Google then searched for the relevant resultType=blob related content in vain and changed it to "resultType=" java.util.map ", and


byte[] b = (byte[]) map.get("text");
String s = new String(b,"utf-8");

Print out s, and the Chinese text will be displayed normally, but the page will still be garbled.

So it's an ajax request, so I check the response header and find the following


Content-Typetext/html;charset=ISO-8859-1

Since the database is uniformly encoded as utf-8, the response header information is modified


@RequestMapping(value = "/queryContentById", method = RequestMethod.GET,produces = "text/plain;charset=UTF-8")
public @ResponseBody String queryContentById(@RequestParam("id") String id) throws SQLException, UnsupportedEncodingException {
  Map map = (Map) ndrService.queryContentById(id);
  byte[] b = (byte[]) map.get("text");
  String s = new String(b,"utf-8");
  return s;
}

Let's look at the problem with another example

1. The Controller of SpringMVC gets garbled code:
(1) add a character set filter to web.xml:

 <!-- Spring Character set filter  --> <filter>  <filter-name>SpringEncodingFilter</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>SpringEncodingFilter</filter-name>  <url-pattern>/*</url-pattern> </filter-mapping>

(2) modify charset= utf-8 "and pageEncoding=" utf-8" on pages such as JSP

2. The Controller reads the correct Chinese, but when saved to the database, it becomes "?? ".

(1) change the database connection jdbc_url = JDBC: mysql: / / localhost: 3306 / mybatistest & # 63; UseUnicode = yes& CharacterEncoding = UTF8 (& amp; "" : "&" in XML file)

(2) change the character set of the database to utf-8: open my.ini in the root directory of mysql (mysql5.6 is my-default.ini, to copy it named my.ini), add (or modify) the following specific location:

[mysqld]character-set-server=utf8 [client]default-character-set = utf8[mysql]default-character-set = utf8

So that's fine on my side.

Review:

Usually the problem of Chinese messy code is due to the character encoding Settings are wrong, I here whether the database or Java files, JSP files, are unified into utf-8. Finally the problem was solved.


Related articles: