SpringBoot 项目中文乱码解决方案

SpringBoot 项目中经常会遇到中文乱码问题,这通常是由于字符集编码不一致导致的。本文介绍几种常见的解决方案,并提供代码示例。

解决方案

  1. application.properties 中添加以下配置:
# 设置字符集编码
spring.http.encoding.charset=utf-8
# 设置请求编码
spring.http.encoding.force-request=true
# 设置响应编码
spring.http.encoding.force-response=true
  1. 在实体类上添加注解,指定字符集为 UTF-8:
@Entity
@Table(name = 'user')
@org.hibernate.annotations.Table(appliesTo = 'user', comment = '用户表')
@Getter
@Setter
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = 'name', nullable = false, columnDefinition = 'varchar(50) COMMENT '姓名'')
    @org.hibernate.annotations.ColumnDefault(''未知'')
    @NotBlank(message = '姓名不能为空')
    @Size(max = 50, message = '姓名长度不能超过50个字符')
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    @JsonProperty('name')
    private String name;

    @Column(name = 'age', nullable = false, columnDefinition = 'int(11) COMMENT '年龄'')
    @org.hibernate.annotations.ColumnDefault('0')
    @Min(value = 0, message = '年龄不能小于0')
    @Max(value = 200, message = '年龄不能大于200')
    @JsonFormat(shape = JsonFormat.Shape.NUMBER_INT)
    @JsonProperty('age')
    private Integer age;

    @Column(name = 'sex', nullable = false, columnDefinition = 'varchar(10) COMMENT '性别'')
    @org.hibernate.annotations.ColumnDefault(''未知'')
    @NotBlank(message = '性别不能为空')
    @Size(max = 10, message = '性别长度不能超过10个字符')
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    @JsonProperty('sex')
    private String sex;

    @Column(name = 'address', nullable = true, columnDefinition = 'varchar(100) COMMENT '地址'')
    @org.hibernate.annotations.ColumnDefault('''')
    @Size(max = 100, message = '地址长度不能超过100个字符')
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    @JsonProperty('address')
    private String address;

    @CreatedDate
    @Column(name = 'created_at', nullable = false, updatable = false, columnDefinition = 'timestamp default current_timestamp COMMENT '创建时间'')
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = 'yyyy-MM-dd HH:mm:ss', timezone = 'GMT+8')
    @JsonProperty('created_at')
    private LocalDateTime createdAt;

    @LastModifiedDate
    @Column(name = 'updated_at', nullable = false, columnDefinition = 'timestamp default current_timestamp on update current_timestamp COMMENT '更新时间'')
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = 'yyyy-MM-dd HH:mm:ss', timezone = 'GMT+8')
    @JsonProperty('updated_at')
    private LocalDateTime updatedAt;
}
  1. @ControllerAdvice 中添加全局异常处理方法,处理乱码异常:
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public Response handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) {
        String message = ex.getCause().getMessage();
        if (message.contains('UTF-8')) {
            return Response.fail('请求参数中存在中文乱码,请检查参数是否正确');
        } else {
            return Response.fail('请求参数解析失败,请检查参数是否正确');
        }
    }
}
  1. 在拦截器中添加过滤器,处理请求和响应中的字符集编码:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Bean
    public FilterRegistrationBean<CharacterEncodingFilter> characterEncodingFilterRegistrationBean() {
        FilterRegistrationBean<CharacterEncodingFilter> registrationBean = new FilterRegistrationBean<>();
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding('UTF-8');
        characterEncodingFilter.setForceEncoding(true);
        registrationBean.setFilter(characterEncodingFilter);
        registrationBean.setName('characterEncodingFilter');
        registrationBean.addUrlPatterns('/*');
        return registrationBean;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                request.setCharacterEncoding('UTF-8');
                response.setContentType('text/html;charset=UTF-8');
                return true;
            }
        }).addPathPatterns('/**');
    }
}

注意:

  • 以上方法可以根据实际情况选择使用,建议使用多个方法结合使用,以确保项目中所有中文都能正常显示。
  • 确保数据库连接字符集也是 UTF-8。
  • 使用 Response.fail() 方法返回错误信息,需要自行实现该方法。
  • 在进行字符串拼接操作时,使用 String.format() 方法可以避免乱码问题。
  • 使用 @JsonFormat 注解可以指定日期时间格式,避免出现时间格式问题。

通过以上方法,可以有效解决 SpringBoot 项目中中文乱码问题,确保项目的正常运行。

SpringBoot 项目中文乱码解决方案

原文地址: https://www.cveoy.top/t/topic/nPI2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录