Home > Java > JavaBase > Solution to garbled value transfer in java

Solution to garbled value transfer in java

Release: 2019-12-12 16:33:18
Original
2087 people have browsed it

Solution to garbled value transfer in java

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";
}
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template