各类乱码解决

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

相关文章
相关标签/搜索