我已将应用程序配置为返回html,json或xml视图。 html和xml视图很好但是json视图有问题。
返回的json始终以“{}&&”
为前缀例如
{} && {"asd":{"name":"Practical Spring LDAP","isbn":"978-1475265453","author":"Balaji Varanasi"}}
用于渲染视图的弹簧配置是
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json"/>
<entry key="xml" value="application/xml"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="prefixJson" value="true"/>
</bean>
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.sam.beans.Book</value>
</list>
</property>
</bean>
</constructor-arg>
</bean>
</list>
</property>
</bean>
样本控制器
@RequestMapping("/getBook")
public String showBook(Model model)
{
model.addAttribute("book", new Book("Practical Spring LDAP", "978-1475265453", "Balaji Varanasi"));
return "book";
}
需要帮助...
更新:为Book
添加类定义@XmlRootElement(name="book")
public class Book
{
private String name;
private String isbn;
private String author;
public Book()
{
}
public Book(String name, String isbn, String author)
{
this.name = name;
this.isbn = isbn;
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
答案 0 :(得分:0)
固定
现在正在使用ModelAndView,在视图中我给了MappingJacksonJsonView。
ModelAndView modelAndView = new ModelAndView(new MappingJacksonJsonView(),"book", new Book("Practical Spring LDAP", "978-1475265453", "Balaji Varanasi"));
不确定使用模型有什么问题。
答案 1 :(得分:0)
将@ResponseBody
与返回类型一起使用,以便为请求提供服务。
@RequestMapping("/getBook")
public @ReponseBody
String showBook(Model model)
{
model.addAttribute("book", new Book("Practical Spring LDAP", "978-1475265453", "Balaji Varanasi"));
return "book";
}