When doing JavaWeb, you will always encounter the problem of garbled Chinese value transmission from time to time. After you change all "ISO-8859-1" to "UTF-8", you still find that the problem still exists It's of no use. So I found a method that works all the time (at least for now), which is to force conversion to "UTF-8" encoding. Look at the code:
@RequestMapping("/success.html") public String success(String userCode, Model model) { try { // 编码转换,防止中文乱码 userCode = new String(userCode.getBytes("ISO-8859-1"), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } log.info("userCode:" + userCode); model.addAttribute("userCode", userCode); return "success"; }
Another way is to add an encoding filter to the configuration web.xml file, which can also achieve Chinese value transmission without garbled characters.
<!-- 编码过滤器 --> <filter> <filter-name>encodingFilter</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> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
For more java knowledge, please pay attention to the java basic tutorial column.
The above is the detailed content of Solution to garbled value transfer in java. For more information, please follow other related articles on the PHP Chinese website!