ServletSpringMvc

web 各种乱码处理

2018-05-12  本文已影响4人  wanggs

乱码处理

字符集主要涉及 2 个方面

文件本身的字符集(文件,数据库存储使用,返回给浏览器端的 html 内容)
程序中编码解码时候使用的字符集(如解析 http 请求的数据)
为了防止乱码,我们规定:所有的字符集都用 UTF-8。

IDEA 设置字符集
image
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<head>
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
</head>

前台网页的 GET 请求以 UTF-8 来解析,pom.xml 里设置 uriEncoding


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

<bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
   <property name="templateEngine"    ref="templateEngine"/>
   <property name="characterEncoding" value="UTF-8"/>
</bean>

由处理 @ResponseBody 返回字符串的 MessageConverter 的编码设置造成的,配置 springmvc-servlet.xml 中的 MessageConverter(去掉 )

<!-- 默认的注解映射支持 -->
<!--<mvc:annotation-driven/>-->
<mvc:annotation-driven>
   <mvc:message-converters register-defaults="true">
       <bean class="org.springframework.http.converter.StringHttpMessageConverter">
           <constructor-arg value="UTF-8" />
       </bean>
   </mvc:message-converters>
</mvc:annotation-driven>

解决Spring MVC @ResponseBody返回中文字符串乱码问题

引起乱码原因为SpringMvc使用的默认处理字符串编码为ISO-8859-1,
具体参考org.springframework.http.converter.StringHttpMessageConverter类中public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");

1.对于需要返回字符串的方法添加注解,如下:
  @RequestMapping(value = "/test",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String test(){
        return "哈哈哎呦喂";
    }
2. 配置文件,如下:
<mvc:annotation-driven>  
    <mvc:message-converters register-defaults="true">  
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">  
            <property name="supportedMediaTypes" value = "text/html;charset=UTF-8" />  
        </bean>  
    </mvc:message-converters>  
</mvc:annotation-driven>  

解决思路:Controller的方法中直接通过response向网络流写入String类型的json数据。

@Controller  
public class HomeController {  
    @RequestMapping(value="/Home/writeJson", method=RequestMethod.GET)  
    public void writeJson(HttpServletResponse response)  
    {  
        ObjectMapper mapper = new ObjectMapper();  
  
        HashMap<String,String> map = new HashMap<String,String>();  
        map.put("1","张三");  
        map.put("2","李四");  
        map.put("3","王五");  
        map.put("4", "Jackson");  
  
        String json = "";  
  
        try  
        {  
            json = mapper.writeValueAsString(map);  
            System.out.println(json);  
  
            //方案二  
            ServletOutputStream os = response.getOutputStream(); //获取输出流  
            os.write(json.getBytes(Charset.forName("GBK"))); //将json数据写入流中  
            os.flush();  
  
            //方案一  
            response.setCharacterEncoding("UTF-8"); //设置编码格式  
            response.setContentType("text/html");   //设置数据格式  
            PrintWriter out = response.getWriter(); //获取写入对象  
            out.print(json); //将json数据写入流中  
            out.flush();  
        }  
        catch(Exception e)  
        {  
            e.printStackTrace();  
        }  
  
        //return "home";  
    }  
}  
还有一种方法:设置 @RequestMapping 的 produces 参数,代码如下所示:

思路:使用 @ResponseBody 注解直接返回json字符串,为了防止中文乱码,将@RequestMapping 的 produces 参数设置成 "text/html;charset=UTF-8" 即可。

@RequestMapping(value="/Home/writeJson", method=RequestMethod.GET, produces = "text/html;charset=UTF-8")  
@ResponseBody  
public Object writeJson(HttpServletResponse response)  
{  
        ObjectMapper mapper = new ObjectMapper();  
  
        HashMap<String,String> map = new HashMap<String,String>();  
        map.put("1","张三");  
        map.put("2","李四");  
        map.put("3","王五");  
        map.put("4", "Jackson");  
  
        String json = "";  
  
        try  
        {  
            json = mapper.writeValueAsString(map);  
            System.out.println(json);  
        }  
        catch(Exception e)  
        {  
            e.printStackTrace();  
        }  
  
        return json;  
}  

Spring MVC中默认的编码格式为“ISO-8859-1”,因此造成乱码。

所有的解决方案都是将编码转为UTF-8,至于方式,这里总结了3种,很明显第三种最好用。
  1. Controller传入参数为的HttpServletRequest类,获取到request,并调用
request.setCharacterEncoding("UTF-8");  

  1. 仍然是使用@RequestParam获取参数,然后调用
str= new String(str.getBytes("ISO-8859-1"),"UTF-8");  

  1. 让参数能自动转为UTF-8呢?其实SpringMVC早就设计好了,在Web.xml中配置字符过滤器如
<!-- 字符过滤器 -->  
    <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>  

需要注意,三种方法使用一个即可,使用两个的话,转两次又成乱码了。

创建数据库的时候,选择 Encoding 为 UTF-8配置 JDBC 连接数据库的字符集为 UTF-8

    
jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8

我输入的中文编码是urf8的,建的库是urf8的,但是插入mysql总是乱码,一堆"???????????????????????"

原url地址是:jdbc:mysql://localhost:3306/comment1

改为:jdbc:mysql://localhost:3306/comment1??useUnicode=true&amp;characterEncoding=UTF-8

在 Tomcat 启动文件 catalina.sh 中加一个 -Dfile.encoding=UTF-8

    
JAVA_OPTS="$JAVA_OPTS -Dfile.encoding=UTF-8"

```
- Windows 配置 Tomcat
> 在 Tomcat 启动文件 catalina.bat 中加一个 -Dfile.encoding=UTF-8
```
    
set "JAVA_OPTS=%JAVA_OPTS% -Dfile.encoding=UTF-8"

```
上一篇 下一篇

猜你喜欢

热点阅读