SpringMVC JSON实现

1.配置ViewResolver

在mvc-dispatcher-servlet.xml中配置ViewResolver

<bean  class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="order" value="1" />
        <property name="mediaTypes">
            <map>//对应不同的数据形式
                <entry key="json" value="application/json" />
                <entry key="xml" value="application/xml" />
                <entry key="htm" value="text/html" />
            </map>
        </property>

2.配置defaultViews

使用org.springframework.web.servlet.view.json.MappingJackson2JsonView工具将model转化为JSON形式

<property name="defaultViews">
            <list>
                <!-- JSON View -->
                <bean  class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
                </bean>
            </list>
        </property>

3.引入相关依赖

在POM.xml中的<properties> 标签中添加

<jackson.version>2.5.4</jackson.version>

然后添加jakson的依赖

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>${jackson.version}</version>
</dependency>

4.书写相关controller

有以下两种写法:
1——

@RequestMapping(value="/{courseId}",method=RequestMethod.GET)
public @ResponseBody Course getCourseInJson(@PathVariable Integer courseId){
        return  courseService.getCoursebyId(courseId);
    }

2——

@RequestMapping(value="/jsontype/{courseId}",method=RequestMethod.GET)
public  ResponseEntity<Course> getCourseInJson2(@PathVariable Integer courseId){
        Course course =   courseService.getCoursebyId(courseId);        
        return new ResponseEntity<Course>(course, HttpStatus.OK);
    }

你可能感兴趣的:(spring,json,mvc)