SpringBoot乱码问题解决

原文链接:莫问博客-SpringBoot乱码问题解决

说明

   使用springboot开发理论上是不会出现乱码的,因为springboot默认编码为UTF-8,但是当客户端编码和服务器编码格式不一致时是会导致乱码的,所以这种情况首先需要和客户端约定请求编码格式,这里我们强制约定为UTF-8

一、修改springboot配置文件,以application.properties为例,增加如下配置

spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8

二、当使用springboot模板进行页面开发时,模版解析乱码

       2,1、不推荐的做法是在controller的@RequestMapping中强行设置编码,如

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

       2.2、实现WebMvcConfigurer类来配置编码,2.0以下的springboot可以通过继承WebMvcConfigurerAdapter来修改,以WebMvcConfigurer为例,代码如下

package com.mybatis.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @author liuxiaoding
 * @Date 2019/11/20
 **/
@Configuration
public class EncodeConfig implements WebMvcConfigurer {
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(responseBodyConverter());
    }

    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(
                Charset.forName("UTF-8"));
        return converter;
    }


}

乱码总结:springboot由于约定大于配置的特性,理论上不会出现乱码,如果出现例请按照文本一和二来配置

三、springboot中使用properties文件乱码

       原因一、properties文件本身编码不对,不是utf8,

                      以idea为例在idea使用的utf-8,而properties文件使用的ascii码。点击File-Setting->File Encodings进行设置

       原因二、当原因一的解决方案不生效时可以试试读取properties设置编码格式,

                     @Component
                     @ConfigurationProperties(prefix = "test")
                     @PropertySource(value = {"classpath:test.properties"}, encoding = "utf-8")

      

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值