且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将对象从控制器返回到ajax在spring mvc

更新时间:2021-07-20 03:24:29


我需要ajax中的这个员工列表

I need this list of employee in ajax

在春天,当你需要对象序列化,反序列化和消息转换。在这种情况下,您需要使用 @RequestBody @ResponseBody 注释控制器处理程序方法。

In spring when you need object serialization, de-serialization and message conversion. in that case you need to annotate your controller handler method with @RequestBody and @ResponseBody.

其中:


  • @ResponseBody :will通知Spring尝试转换其返回值并自动将其写入http响应。

  • @RequestBody :将通知Spring尝试转换

  • @ResponseBody : will inform spring that try to convert its return value and write it to the http response automatically.
  • @RequestBody : will inform spring that try to convert the content of the incoming request body to your parameter object on the fly.

在您需要JSON类型的情况下,您必须添加 @ResponseBody 到你的方法签名或者刚刚上面的方法,并生成和可选的消费,如:

in your case you need JSON type, you have to add @ResponseBody to your method signature or just above the method, and produces and consumes which are optional, like:

@RequestMapping(value="phcheck", method=RequestMethod.GET
                produces="application/json")
public @ResponseBody List<Employee> pay(@RequestParam("empid") int empid, String fdate, String tdate) {

  //get your employee list here
  return empList;
}

并在AJAX调用中使用:

and in AJAX call use:


  • contentType:'application / json'属性指示您要发送的数据类型。和

  • dataType:json 属性告诉jquery响应的内容类型。

  • contentType: 'application/json' attribute tells the type of data you're sending. and
  • dataType: json attribute tells jquery what content type of response will receive.

在您的案例 contentType:'application / json'不需要,默认一个 / x-www-form-urlencoded; charset = UTF-8'就足够了。

in your case contentType: 'application/json' is not needed, default one i.e. 'application/x-www-form-urlencoded; charset=UTF-8' is enough.

你可以接收AJAX成功的员工列表,

and you can receive list of employees in your AJAX success, to iterate over it do like:

  success: function (data) {
          $.each(data, function(index, currEmp) {
             console.log(currEmp.name); //to print name of employee
         });    
        },



em> Jackson mapper 或任何其他映射器应该可以在buildpath中使用,以便使用JSON序列化和反序列化。


Note: Jackson mapper or any other mapper should be available on buildpath in order to work JSON serialize and deserialize.

另请参阅:

  • New features in spring mvc 3.1