返回数据
@RequestMapping ( "/showData1" )
public void showData1 ( HttpServletResponse httpServletResponse) throws IOException {
httpServletResponse. getWriter ( ) . println ( "message" ) ;
}
@RequestMapping ( "/showData2" )
@ResponseBody
public String showData2 ( ) {
return "{'name':'thenema'}" ;
}
返回JSON数据
方式一:基于response返回数据的简化格式,返回JSON数据
@RequestMapping ( "/showData3" )
@ResponseBody
public String showData3 ( ) throws JsonProcessingException {
Book book = new Book ( ) ;
book. setName ( "《抽卡入门》" ) ;
book. setPrice ( 648d ) ;
ObjectMapper om = new ObjectMapper ( ) ;
return om. writeValueAsString ( book) ;
}
返回JSON数据(对象)
方式二:使用SpringMVC提供的消息类型转换器将对象和集合数据自动转换为JSON数据
@RequestMapping ( "/showData4" )
@ResponseBody
public Book showData4 ( ) {
Book book = new Book ( ) ;
book. setName ( "《抽卡入门》" ) ;
book. setPrice ( 648d ) ;
return book;
}
< bean class = " org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" >
< property name = " messageConverters" >
< list>
< bean class = " org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
</ list>
</ property>
</ bean>
返回JSON数据(集合)
@RequestMapping ( "/showData5" )
@ResponseBody
public List showData5 ( ) {
Book book1 = new Book ( ) ;
book1. setName ( "《抽卡入门》" ) ;
book1. setPrice ( 648d ) ;
Book book2 = new Book ( ) ;
book2. setName ( "《抽卡入门》" ) ;
book2. setPrice ( 648d ) ;
ArrayList al = new ArrayList ( ) ;
al. add ( book1) ;
al. add ( book2) ;
return al;
}
返回JSON数据
< mvc: annotation-driven/>
< bean class = " org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" >
< property name = " messageConverters" >
< list>
< bean class = " org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
</ list>
</ property>
</ bean>
@Configuration
@ComponentScan ( "com.thenema" )
@EnableWebMvc
public List SpringMvcConfiguration ( ) {
}
响应