消息轉換器的主要作用是,將對象轉換成響應體。說起來,也是一把辛酸淚,搞了一整天。
定製消息轉換器,需要繼承抽象類AbstractHttpMessageConverter
,而且需要指定Content-Type
,這一步非常重要,否則該定製消息轉換器不會被調用
。這一點非常重要,我就是在這一點上,搞了一整天。
控制器
package org.spring;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.IOException;
@Controller
public class HelloController {
@ResponseBody
@RequestMapping(path = "/hello")
public Person execute() throws IOException {
Person person = new Person();
person.setName("中國加油!武漢加油!");
return person;
}
}
Person類
package org.spring;
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
定製消息轉換器
package org.spring;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import java.io.IOException;
import java.nio.charset.Charset;
public class MyMessageConverter extends AbstractHttpMessageConverter<Person> {
public MyMessageConverter() {
super(Charset.forName("utf-8"),
new MediaType("text", "my-html"));
}
@Override
protected boolean supports(Class<?> aClass) {
return Person.class == aClass;
}
@Override
protected Person readInternal(Class<? extends Person> aClass, HttpInputMessage httpInputMessage)
throws IOException, HttpMessageNotReadableException {
return null;
}
@Override
protected void writeInternal(Person person, HttpOutputMessage httpOutputMessage)
throws IOException, HttpMessageNotWritableException {
httpOutputMessage.getBody().write(person.getName().getBytes("utf-8"));
}
}
必須在構造方法中指定Content-Type
,可以用自己定義的內容類型,而不侷限於html
之類。boolean supports
方法,起到了過濾器的作用,當返回true
時,支持對傳入對象進行轉換。其他兩個方法,用於將對象寫入響應體和用請求體填充對象。值得一提的是,對字符串取字節數組時,應該指明編碼類型
,否則如果內容中有中文會導致亂碼。