LoginSignup
0
0

More than 5 years have passed since last update.

Springでbeanプロパティがリスト形式のリクエストパラメータをバインドする方法

Last updated at Posted at 2019-02-17

リスト形式のリクエストパラメータをバインドする方法

以下のコードでbeanプロパティがリスト形式の場合のリクエストパラメータをバインドできます。


<body>
    <form action="/sample/bean" method="post">
        <table>
            <tr>
                <td>入力1:price:</td>
                <td><input type="text" name="sampleBean.childBean[0].price"></td>
                <td>入力1:unit:</td>
                <td><input type="text" name="sampleBean.childBean[0].unit"></td>
            </tr>
            <tr>
                <td>入力2:price:</td>
                <td><input type="text" name="sampleBean.childBean[1].price"></td>
                <td>入力2:unit:</td>
                <td><input type="text" name="sampleBean.childBean[1].unit"></td>
            </tr>
        </table>
    </form>
</body>
@Controller
public class SampleController {

    @RequestMapping(value="/sample/bean", method=RequestMethod.POST)
    public String goUserCreateErrorPage(SampleBean sampleBean) {
        return "sample";
    }
}
public class SampleBean {
  private String childBeanUnit;
  private List<SampleChildBean> childBean;
}
getter,setterは略

public class SampleChildBean {
    private String price;
    private String unit;
}
getter,setterは略

ポイント

今回の場合はinputのname属性の定義の仕方にポイントがあります。
一つずつ解説していくと、
解説1:Controller側の@RequestMappingメソッドの引数で指定しているバインド対象の引数名
解説2:バインド対象引数のクラスで定義されているプロパティ名を指定
    更にリストなので、index番号も指定する。
解説3:最後に解説2で指定しているプロパティのクラスが持つプロパティを指定する(ややこしい?)

<input type="text" name="sampleBean.childBean[0].price">
                            解説1      解説2     解説3

終わりに

一旦、忘れないうちに書いてみたのは良いものの、説明がいまいちなので、
時間あるときにもう少しましな説明を考えよう、、笑

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0