我有一个处理ajax调用并返回JSON的控制器方法。我正在使用json.org的JSON库来创建JSON。
我可以做以下事情:
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public String getJson()
{
JSONObject rootJson = new JSONObject();
// Populate JSON
return rootJson.toString();
}
但将JSON字符串放在一起效率很低,只是让Spring将它写入响应的输出流。
相反,我可以将它直接写入响应输出流,如下所示:
@RequestMapping(method = RequestMethod.POST)
public void getJson(HttpServletResponse response)
{
JSONObject rootJson = new JSONObject();
// Populate JSON
rootJson.write(response.getWriter());
}
但似乎有更好的方法来做到这一点,而不是诉诸于将HttpServletResponse
传递给处理程序方法。
是否可以从我可以使用的处理程序方法返回另一个类或接口,以及@ResponseBody
注释?
答案 0 :(得分:31)
您可以将输出流或Writer作为控制器方法的参数。
@RequestMapping(method = RequestMethod.POST)
public void getJson(Writer responseWriter) {
JSONObject rootJson = new JSONObject();
rootJson.write(responseWriter);
}
@see Spring Reference Documentation 3.1 Chapter 16.3.3.1 Supported method argument types
P.S。我觉得使用OutputStream
或Writer
作为参数在测试中使用起来比HttpServletResponse
更容易 - 并且感谢关注what I have written; - )< / p>
答案 1 :(得分:4)
最后,我为此写了HttpMessageConverter
。有了它,我可以做到以下几点:
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public JSONObject getJson()
throws JSONException
{
JSONObject rootJson = new JSONObject();
// Populate JSON
return rootJson;
}
这是我的HttpMessageConverter
课程:
package com.example;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpMessage;
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;
public class JsonObjectHttpMessageConverter
extends AbstractHttpMessageConverter<JSONObject>
{
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
public JsonObjectHttpMessageConverter()
{
super(new MediaType("application", "json"), new MediaType("text", "javascript"));
}
@Override
protected boolean supports(Class<?> clazz)
{
return JSONObject.class.equals(clazz);
}
@Override
protected JSONObject readInternal(Class<? extends JSONObject> clazz,
HttpInputMessage inputMessage)
throws IOException,
HttpMessageNotReadableException
{
throw new UnsupportedOperationException();
}
@Override
protected void writeInternal(JSONObject jsonObject,
HttpOutputMessage outputMessage)
throws IOException,
HttpMessageNotWritableException
{
PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputMessage.getBody(),
getContentTypeCharset(outputMessage)));
try
{
jsonObject.write(writer);
writer.flush();
}
catch (JSONException e)
{
throw new HttpMessageNotWritableException(e.getMessage(), e);
}
}
private Charset getContentTypeCharset(HttpMessage message)
{
MediaType contentType = message.getHeaders().getContentType();
Charset charset = (contentType != null) ? contentType.getCharSet() : null;
return (charset != null) ? charset : DEFAULT_CHARSET;
}
}
HttpMessageConverter
必须在Spring注册。这可以在dispatcher-servlet.xml
文件中完成,如下所示:
<beans ...>
...
<mvc:annotation-driven conversion-service="conversionService" validator="validator">
<mvc:argument-resolvers>
...
</mvc:argument-resolvers>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
<value>*/*</value>
</list>
</property>
<property name="writeAcceptCharset" value="false" />
</bean>
<bean class="com.example.JsonObjectHttpMessageConverter" />
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper" ref="jacksonObjectMapper" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
...
</beans>
如您所见,我还注册了其他HttpMessageConverter
个对象。订单很重要。
答案 2 :(得分:1)
请注意,如果您使用OutputStream或Writer,则需要您自己编写标题。
一种解决方法是使用InputStreamResource / ResourceHttpMessageConverter