1. 程式人生 > >解決Spring Mvc中對象綁定參數重名的問題

解決Spring Mvc中對象綁定參數重名的問題

uid NPU public double method 修改 名稱 ble size

html頁面

<form method=‘post‘ action=‘url‘>
     用戶名 <input type=‘text‘ name=‘name‘>
     用戶id <input type=‘text‘ name=‘id‘>
     食品名 <input type=‘text‘ name=‘name‘>
     食品id <input type=‘text‘ name=‘id‘>
     <input type=‘text‘ name=‘age‘>
     <input type=‘text‘ 
name=‘price‘> </form>

實體類

public class User{
   private String name;
   private String id;
   private Integer age;
   //getter 和setter
}
----------------------------------
public class Food{
   private String name;
   private String id;
   private Double price,
   //getter 和setter
}

controller

@requestMap(value={‘/order/book‘})
public string show(User u,Food f){}

在上述情況下User 和food都不能得到正確的name和id,或者說更本得不到

1.建立一個中間橋梁, 拆分有所的屬性

建立一個中間橋梁UserFoodDto對象

public class UserFoodDto{
  private String uid; //用戶id
  private String uname; //用戶名
  private String fid; //食物id
  private String fname; //食物名稱
  private
Double price, //食物價格   private Integer age; //用戶年齡      //getter 和setter }

修改前臺頁面的 name值

<form method=‘post‘ action=‘url‘>
  用戶id <input type=‘text‘ name=‘uid‘>
  用戶名 <input type=‘text‘ name=‘uname‘>
  食品id <input type=‘text‘ name=‘fid‘>
  食品名 <input type=‘text‘ name=‘fname‘>
  <input type=‘text‘ name=‘age‘>
  <input type=‘text‘ name=‘price‘>
</form>

controller

@requestMapping(value={‘/order/book‘})
public string show(UserFoodDto dto){
  //創建用戶和食物實例
  User u = new User();
  Food f = new Food();
   //分別設置屬性
  u.setUid(dto.getUid());
  f.setFid(dto.getFid());
  u.setName(dto.getUname());   f.setName(dto.getFname());   u.setAge(dto.getAge);   f.setPrice(dto.getPrice);   ..... }

缺點是:如果數據量大,100百個字段,修改的地方很多,而且一個dto,拆分也很費力,因此不建議在數據量大的情況下使用

2.使用橋連接,拆分沖突的屬性

前端頁面

<form method=‘post‘ action=‘url‘>
  用戶名 <input type=‘text‘ name=‘uname‘>
  用戶id <input type=‘text‘ name=‘uid‘>
  食品名 <input type=‘text‘ name=‘fname‘>
  食品id <input type=‘text‘ name=‘fid‘>
  <input type=‘text‘ name=‘age‘>
  <input type=‘text‘ name=‘price‘>
</form>

中間橋梁類

---將沖突的字段專門建立一個javaBean
public Class UFBridge{ 
  private String uname;
  private String uid;
  private String fname;
  private String fid;
}

controller

@requestMapping(value={‘/order/book‘})
public string show(User u,Food f,UFBridge ufb){
  u.setId(ufb.getUid);
  u.setName(ufb.getUname());

  f.setId(ufb.getFid);
  f.setName(ufb.getUname());
}

3.創建一個類包含User和Food

vo對象

public class UserFoodVo{
  private User user;
  private Food food;
  //省略getter和setter方法
}

前臺頁面

<form method=‘post‘ action=‘url‘>
  用戶名 <input type=‘text‘ name=‘user.name‘>
  用戶id <input type=‘text‘ name=‘user.id‘>
  食品名 <input type=‘text‘ name=‘food.name‘>
  食品id <input type=‘text‘ name=‘food.id‘>
  <input type=‘text‘ name=‘user.age‘>
  <input type=‘text‘ name=‘food.price‘>
</form>

controller

@requestMapping(value={‘/order/book‘})
public string show(UserFoodVo vo){}

解決Spring Mvc中對象綁定參數重名的問題