后台用对象接收http请求的数据

首先我的数据库里有一个user表,并且有id,name,password属性。

实体User类:

package models;

import javax.persistence.Entity;

import play.db.jpa.Model;

@Entity
public class User extends Model {
  private String name;
  private String password;
  //不需要定义id属性,因为Model里有id属性

  public Long getId() {
    return id;
  }
  public void setId(Long id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getPassword() {
    return password;
  }
  public void setPassword(String password) {
    this.password = password;
  }

  public User(String name, String password) {
    super();
    this.name = name;
    this.password = password;
  }
  public User(Long id, String name, String password) {
    super();
    this.id = id;
    this.name = name;
    this.password = password;
  }
  public User() {
    super();
  }

}

HTML:

<button ng-click=test()>测试</button>

JS:

  $scope.test = function() {
    var id = 1;
    $http({
      method: 'GET',
      url: '/Application/test?user.id=' + id,
    }).then(function successCallback(response) {
      // 请求成功执行代码
    }, function errorCallback(response) {
      // 请求失败执行代码
    });
  }

后台控制器:

  public static void test(User user) {
    System.out.println(user.getName() + user.getPassword());
    String s = params.get("user.id");

    System.out.println(s);
  }

后台能够拿到数据,原理就是

POJO对象绑定

使用同样的命名转换规则,Play也可自动对任何model类进行绑定。

public static void create(Client client ) {

    client.save();

    show(client);

}

使用上面这个create方法,创建一个client的查询字符串可以是下面这个样式:

?client.name=Zenexity&client.email=contact@zenexity.fr

Play将创建一个Client实例,同时把从http参数里取得的值赋值给对象中与http参数名同名的属性。不能明确的参数将被安全忽略,类型不匹配的也会被安全忽略。

参数绑定是通过递归来实现的,也就是说你可以采用如下的查询字符串来编辑一个完整的对象图(object graphs):

?client.name=Zenexity

&client.address.street=64+rue+taitbout

&client.address.zip=75009

&client.address.country=France

使用数组标记(即[])来引用对象的id,可以更新一列模型对象。比如,假设Client模型有一列Customer模型声明作为List Customer customers。为了更新这列Customers对旬,你需要提供如下查询字符串:

?client.customers[0].id=123

&client.customers[1].id=456

&client.customers[2].id=789

JPA 对象绑定

使用http到java的绑定,可以自动绑定一个JPA对象。

比如,在http参数里提供了user.id字段,当play找到id字段里,play将从数据库加载匹配的实例进行编辑,随后会自动把其他通过http请求提供的参数应用到实例里,因此在这里可以直接使用save()方法,如下:

public static void save(User user) {

    user.save(); // ok with 1.0.1

}

和在POJO映射里采取的方式相同,你可以使用JPA绑定来编辑完整的对象图(object graphs),唯一区别是你必须为每个打算编辑的子对象提供id:

user.id = 1

&user.name=morten

&user.address.id=34

&user.address.street=MyStreet 

posted on 2018-02-08 11:19  zhengbiyu  阅读(2963)  评论(0编辑  收藏  举报