Spring MVC JSON (JSON to Java)(pull)

15 篇文章 1 订阅
3 篇文章 1 订阅

sing Spring MVC we can send to the client data in JSON format, but what if the client sends POST request with data in JSON format? Here we will see how Spring MVC “auto” maps JSON data sent by client POST request into Java object.

 

Objectives:

  • How client request “GET” data in json format?
  • How client send “POST” data in json format using jQuery.ajax()?
  • How Spring MVC Controller can map json into java object?

Environment:

  • Eclipse
  • Maven (optional)
  • Browser (Firefox, Chrome or IE)
  • Java Server  (Jetty, Apache,…)

Libraries:

  • Spring Framework
  • Jackson
  • jQuery
 <dependencies>
        <dependency><!-- spring mvc -->
            <groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>3.0.5.RELEASE</version>
        </dependency>
        <dependency><!-- jackson -->
            <groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.4.2</version>
        </dependency>
    </dependencies>

( 1 ) Java Project

( 2 ) Java Code & XML Configuration

  • RestController.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.hmkcode.controllers;
 
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
 
import com.hmkcode.vo.Person;
 
@Controller
@RequestMapping ( "/cont" )
public class RestController {
 
   public RestController(){
       System.out.println( "init RestController" );
   }
 
   //this method responses to GET request http://localhost/spring-mvc-json/rest/cont
   // return Person object as json
 
   @RequestMapping (method = RequestMethod.GET)
   public @ResponseBody Person get(HttpServletResponse res) {
 
       Person person = new Person();
       person.setId( 1 );
       person.setName( "hmk" );
 
       return person;
   }
 
   //this method response to POST request http://localhost/spring-mvc-json/rest/cont/person
   // receives json data sent by client --> map it to Person object
   // return Person object as json
   @RequestMapping (value= "person" , method = RequestMethod.POST)
   public @ResponseBody Person post( @RequestBody final  Person person) {    
 
       System.out.println(person.getId() + " " + person.getName());
       return person;
   }
}
  • Person.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
package com.hmkcode.vo;
 
import java.io.Serializable;
 
public class Person implements Serializable {
 
   private static final long serialVersionUID = 1L;
   private int id;
   private String name;
 
//getters and setters...
 
}
  • rest-servlet.xml
?
1
2
3
4
5
6
< beans ...>
 
   < context:component-scan base-package = "com.hmkcode.controllers" />
   < mvc:annotation-driven />
 
</ beans >
  • web.xml
?
1
2
3
4
5
6
7
8
9
10
.......
  < servlet >
     < servlet-name >rest</ servlet-name >
     < servlet-class >org.springframework.web.servlet.DispatcherServlet</ servlet-class >
   </ servlet >
 
   < servlet-mapping >
     < servlet-name >rest</ servlet-name >
     < url-pattern >/rest/*</ url-pattern >
   </ servlet-mapping >
  • index.html –> $.ajax()
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<html>
......
   <script src= "http://code.jquery.com/jquery-1.9.1.js" ></script>
<script type= "text/javascript" >
$(document).ready( function (){
   sendAjax();
});
 
function sendAjax() {
 
$.ajax({
     url: "/spring-mvc-json/rest/cont/person" ,
     type: 'POST' ,
     dataType: 'json' ,
     data: "{\"name\":\"hmkcode\",\"id\":2}" ,
     contentType: 'application/json' ,
     mimeType: 'application/json' ,
     success: function (data) {
         alert(data.id + " " + data.name);
     },
     error: function (data,status,er) {
         alert( "error: " +data+ " status: " +status+ " er:" +er);
     }
});
}
</script>
......
</html>

( 3 ) Run & Test

  • Run Jetty “or your” server
  • http://localhost:8080/spring-mvc-json/rest/cont
  • Thsi url will call the first method RestController.get() return Person object in json format

  • http://localhost:8080/spring-mvc-json/index.html
  • This html page contains jQuery.ajax() function that will call the second method RestController.post() on the load of the paeg.
  • $.ajax() will send json data data: “{\”name\”:\”hmkcode\”,\”id\”:2}”
  • Controller will receive this json data mapp into java object using @RequestBody
  • Controller will return data again to the client in json format too.

Soruce Code: @ github

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值