各類亂碼解決

1.請求URL帶中文

URL:http://localhost:8080/demo-web/file/download.do?file=季度.txthtml

解決方法:java

在tomcat/conf/server.xml中加入URIEncoding配置web

<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding='UTF-8' />

 

2.使用@ResponseBody返回String類型帶中文

@RequestMapping("upload")
@ResponseBody
public String upload(String name ,Part file) throws IOException,DemoException{
    if(file.getSize() > FILE_MAX_SIZE){
        throw new DemoException("文件過大");
    }

    //獲取文件名
    String fileName = PartUtils.getFileName(file);

    InputStream is = file.getInputStream();
    FileUtils.copyInputStreamToFile(is, new File("D:\\upload\\" + fileName));

    return name+":"+fileName;
}

解決方法:spring

    返回String類型使用StringHttpMessageConverter轉化器,其中默認編碼是ISO-8859-1;只須要編碼改成UTF-8便可。tomcat

    Spring-mvc配置以下mvc

<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
    <constructor-arg value="UTF-8"/>
</bean>
<mvc:annotation-driven>
    <mvc:message-converters>
        <!--StringHttpMessageConverter中文亂碼-->
        <ref bean="stringHttpMessageConverter"/>
    </mvc:message-converters>
</mvc:annotation-driven>

 

補充(2017-05-04)另一個解決方案 :app

@RequestMapping(value="sayHello",produces = "text/html;charset=utf-8")

 

3.下載文件名帶中文

使用java.net.URLEncoder.encode(fileName, "UTF-8")編碼轉化。編碼

response.setHeader("Content-Disposition", "attachment; filename="+java.net.URLEncoder.encode(fileName, "UTF-8"));

 

4.IDEA控制輸出帶中文

在VM options:-Dfile.encoding=UTF-8spa

相關文章
相關標籤/搜索