Recently, using Ajax to request springmvc background to query the mysql database, the page shows garbled Chinese code
Initially configured in mybatis 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 text value found in this way is always displayed in garbled code in the console.
After that, Google searched for relevant resultType=blob related content without success, so it 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 is displayed normally at this time, but the page display is still garbled.
Therefore, it is ajax request, so check the response header information 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 another example problem
1. SpringMVC's Controller gets garbled code:
(1) Add a character set filter to web.xml:
Copy the code as follows: <!-- Spring character set filter--><filter><filter-name>SpringEncodingFilter</filter-name><filter-class>org.springframework.web.filter.Character EncodingFilter</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-p attern> /*</url-pattern></filter-mapping>
(2) Modify on JSP and other pages: charset=UTF-8" and pageEncoding="UTF-8"
2. The Controller reads the correct Chinese, but after saving it to the database, it becomes "??"
(1) Modify the database connection jdbc_url=jdbc:mysql://localhost:3306/mybatistest?useUnicode=yes&characterEncoding=UTF8("&": means "&" in the xml file)
(2) Modify the character set of the database to utf-8: Open my.ini in the root directory of mysql (mysql5.6 is my-default.ini, and copy it as my.ini), and add it in the specific location below (or modified):
The code copy is as follows: [mysqld]character-set-server=utf8 [client]default-character-set = utf8[mysql]default-character-set = utf8
There is no problem with setting it on my side.
Summary:
Usually, the problem of Chinese garbled code is caused by incorrect character encoding settings. Whether it is the database, Java file, or JSP file, it is unified into UTF-8. Finally the problem was solved.