场景
1.SpringBoot自动配置了消息转化器。
2.自定义消息转化器,只需要在类中添加消息转化器的@Bean,就会被SpringBoot自动加入到容器中。
实现
新建Controller
package com.example.demo.controller;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@EnableAutoConfiguration
public class TestMessageConvertController {
//定义消息转换器
//SpringBoot默认配置了消息转换器
@Bean
public StringHttpMessageConverter stringHttpMessageConverter() {
StringHttpMessageConverter stringHttpMessageConverter =new StringHttpMessageConverter(Charset.forName("ISO8859-1"));
return stringHttpMessageConverter;
}
@RequestMapping("/testMessageConvert")
@ResponseBody
public String testMessageConvert() {
return "你好!!!";
}
public static void main(String[] args) {
SpringApplication.run(TestMessageConvertController.class, args);
}
}
运行项目,打开浏览器输入:
http://localhost:8080/testMessageConvert
由此可见,SpringBoot自带编码过滤器,即使是中文也不会乱码。
实现自定义编码过滤器
package com.example.demo.controller;
import java.nio.charset.Charset;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@EnableAutoConfiguration
public class TestMessageConvertController {
//定义消息转换器
//SpringBoot默认配置了消息转换器
@Bean
public StringHttpMessageConverter stringHttpMessageConverter() {
StringHttpMessageConverter stringHttpMessageConverter =new StringHttpMessageConverter(Charset.forName("ISO8859-1"));
return stringHttpMessageConverter;
}
@RequestMapping("/testMessageConvert")
@ResponseBody
public String testMessageConvert() {
return "你好!!!";
}
public static void main(String[] args) {
SpringApplication.run(TestMessageConvertController.class, args);
}
}
再运行项目,刷新浏览器