????? 在搭建spring mvc rest环境时遇些问题:
问题1:
????? 当Controller返回Object时,请求json数据返回的内容和我期望的不一致,例如返回的Object是User类有个name属性,原本希望返回{"name":'姓名'}这样的数据,结果返回{"user":{"name":"姓名"}}。
问题原因:
????? org.springframework.web.servlet.view.json.MappingJacksonJsonView类的filterModel方法返回的是key为user的Map对象,而实际我想要的效果是直接返回User对象。
解决办法:
????? 继承MappingJacksonJsonView类,重写filterModel方法
protected Object filterModel(Map<String, Object> model) { Map<?, ?> result = (Map<?, ?>) super.filterModel(model); if (result.size() == 1) { return result.values().iterator().next(); }else{ return result; } }
问题2:
????? 当Controller返回Object时,请求xml数据返回的内容和预期的不一致。Controller明明返回的是User结果xml返回的是org.springframework.validation.BindingResult对象
问题原因:
????? org.springframework.web.servlet.view.xml.MarshallingView类的locateToBeMarshalled方法接受的参数Map<String, Object> model里有2个对象分别是BindingResult和User,locateToBeMarshalled方法在返回时候先检索到BindingResult结果就返回了它而不是真正需要返回的User
for (Object o : model.values()) { if (o != null && this.marshaller.supports(o.getClass())) { return o;, } }
解决办法:
????? 继承MarshallingView类重写locateToBeMarshalled方法,由于MarshallingView类没有提供marshaller,和modelKey的get方法,所以还要重写这2个属性相关的内容,完整代码如下
public class MarshallingView extends org.springframework.web.servlet.view.xml.MarshallingView{ private Marshaller marshaller; private String modelKey; public Marshaller getMarshaller() { return marshaller; } public String getModelKey() { return modelKey; } public MarshallingView() { super(); } public MarshallingView(Marshaller marshaller) { super(marshaller); this.marshaller = marshaller; } @Override public void setMarshaller(Marshaller marshaller) { super.setMarshaller(marshaller); this.marshaller = marshaller; } @Override public void setModelKey(String modelKey) { super.setModelKey(modelKey); this.modelKey = modelKey; } @Override protected Object locateToBeMarshalled(Map<String, Object> model) throws ServletException { if (this.getModelKey() != null) { Object o = model.get(this.getModelKey()); if (o == null) { throw new ServletException("Model contains no object with key [" + modelKey + "]"); } if (!this.getMarshaller().supports(o.getClass())) { throw new ServletException("Model object [" + o + "] retrieved via key [" + modelKey + "] is not supported by the Marshaller"); } return o; } for (Object o : model.values()) { if (o != null && !(o instanceof BindingResult) && this.getMarshaller().supports(o.getClass())) { return o; } } return null; } }
?其实关键的修改只有
!(o instanceof BindingResult)
这一句,在返回时候跳过BindingResult类。
?