后台用對象接收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 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM