[关闭]
@dume2007 2017-03-01T02:39:23.000000Z 字数 2184 阅读 5835

Spring Boot保存中文内容到MySQL数据库乱码

springMVC Spring-Boot gradle java


方法1. 修改配置文件application.properties

其实Spring Boot默认配置UTF-8为默认编码,但是在实际开发中会发现保存数据到MySQL数据库时中文是乱码。

Spring Boot文档中默认配置:

  1. spring.http.encoding.charset=UTF-8 # Charset of HTTP requests and responses. Added to the "Content-Type" header if not set explicitly.
  2. spring.http.encoding.enabled=true # Enable http encoding support.

而相关的配置会在HttpEncodingAutoConfiguration中使用

  1. @Bean
  2. @ConditionalOnMissingBean(CharacterEncodingFilter.class)
  3. public CharacterEncodingFilter characterEncodingFilter() {
  4. CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
  5. filter.setEncoding(this.properties.getCharset().name());
  6. filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));
  7. filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));
  8. return filter;
  9. }

而这里你其实可以看到,默认情况下forceRequestEncoding和forceResponseEncoding是为false的。在配置中自己加上一行:

  1. spring.http.encoding.force=true

那么框架默认用的是utf8编码,那就是数据库默认设置问题了,所以新建数据库的时候编码应该默认选择utf8,然后在application.properties配置中指定utf8格式:

  1. spring.jpa.hibernate.ddl-auto=update
  2. spring.datasource.url=jdbc:mysql://192.168.99.100:3306/db_example?useUnicode=true&characterEncoding=utf-8
  3. spring.datasource.username=root
  4. spring.datasource.password=123456

方法2. 修改web.xml

如果是早起版本的spring,需配置web.xml,需加上以下几行:

  1. <filter>
  2. <filter-name>CharacterEncodingFilter</filter-name>
  3. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  4. <init-param>
  5. <param-name>encoding</param-name>
  6. <param-value>utf-8</param-value>
  7. </init-param>
  8. <init-param>
  9. <param-name>forceEncoding</param-name>
  10. <param-value>true</param-value>
  11. </init-param>
  12. </filter>
  13. <filter-mapping>
  14. <filter-name>CharacterEncodingFilter</filter-name>
  15. <url-pattern>/*</url-pattern>
  16. </filter-mapping>

然后修改applicationContext.xml数据源格式:

  1. <property name="url" value="jdbc:mysql://192.168.99.100:3306/db_example?useUnicode=true&characterEncoding=utf-8"></property>

Spring Boot简介

Spring Boot理念就是零配置编程,让我们彻底告别xml配置文件,利用spring早已推广的annotation来代替各类xml文件。

要使用spring-boot,首先要使用spring-annotation
对于所有的bean要标注:@Component
切面要标注:@Aspect, @Pointcut, @After
对于主类,要标注:@Configuration, @Componentscan
之后spring-boot会自行搜索所有的标注了component等标记的类,并在spring中注册。

为了能够使注册生效,对于需要调用的类,不能直接New,必须使用spring的ApplicationContext的getBean()方法生成才行。

SpringMVC运行流程图

此处输入图片的描述

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注