1. 程式人生 > >SprngBoot字元編碼處理

SprngBoot字元編碼處理

SpringBoot的字符集配置類

	org.springframework.boot.autoconfigure.http.HttpEncodingProperties

可配置屬性
在這裡插入圖片描述
屬性配置中預設為UTF8編碼

SpringBoot中字符集AutoConfiguration類

	org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration

HttpEncodingAutoConfiguration配置了Bean

  • CharacterEncodingFilter:根據字符集引數配置了過濾器處理字符集
  • LocaleCharsetMappingsCustomizer:根據Local處理不同的字符集
    在這裡插入圖片描述

具體實現設定字符集的類CharacterEncodingFilter

	@Override
	protected void doFilterInternal(
			HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		String encoding = getEncoding();
		if (encoding != null) {
			if (isForceRequestEncoding() || request.getCharacterEncoding() == null) {
				request.setCharacterEncoding(encoding);
			}
			if (isForceResponseEncoding()) {
				response.setCharacterEncoding(encoding);
			}
		}
		filterChain.doFilter(request, response);
	}

HttpMessageConverter

StringHttpMessageConverter是SpringMVC的訊息轉換器介面,用來處理請求報文到字串和字串到響應報文的轉換器

	private Charset getContentTypeCharset(@Nullable MediaType contentType) {
		if (contentType != null && contentType.getCharset() != null) {
			return contentType.getCharset();
		}
		else {
			Charset charset = getDefaultCharset();
			Assert.state(charset != null, "No default charset");
			return charset;
		}
	}

StringHttpMessageConverter預設先根據ContentType中設定的字符集處理訊息如果ContentType中沒有設定字符集則使用StringHttpMessageConverter中定義的預設字符集。StringHttpMessageConverter預設定義的是ISO-8859-1字符集
需要其它字符集的自己配置StringHttpMessageConverter的Bean。
在這裡插入圖片描述

  • SpringBoot中配置StringHttpMessageConverter
	org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration

配置了StringHttpMessageConverter的字符集

	@Bean
		@ConditionalOnMissingBean
		public StringHttpMessageConverter stringHttpMessageConverter() {
			StringHttpMessageConverter converter = new StringHttpMessageConverter(
					this.encodingProperties.getCharset());
			converter.setWriteAcceptCharset(false);
			return converter;
		}