JavaのWebアプリケーション開発フレームワークによる、Webサイト開発の顛末記です。

EclipseのMavenを使った、Spring-MVC、Thymeleaf、MyBatis 等のプログラミングテクニックを、
備忘録的に記録しています。実際に動くソースコードを多用して説明していますので、
これからEclipseや、Spring-MVCを始めたいと思っている人にとって、少しでも参考になれば幸いです。
Spring-MVCの散歩道 > 応用の森(JSON編) > JSONデータ構造から動的クラス生成

package jp.dip.arimodoki.cntl;

import java.net.URLDecoder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import jp.dip.arimodoki.blogic.BlZipIf;
import jp.dip.arimodoki.common.CConst;
import jp.dip.arimodoki.common.JsonConvertIf;
import jp.dip.arimodoki.model.FormZipIf;
import jp.dip.arimodoki.model.JsonReqAreaIf;

/**
 * JSON動的Class作成サンプル
 */
@Scope("prototype")
@Controller
public class ZipCode implements CConst {
    //JSON パーサー/ジェネレータインスタンスをDI
    @Autowired
    private JsonConvertIf jsonConvert;

    //リクエストJSONパース結果格納クラスインスタンスをDI
    @Autowired
    private JsonReqAreaIf jsonReqArea;

    /**
     * リクエスト/レスポンス用データモデルクラス
     */
    @Autowired      //データモデルオブジェクトをDI
    private FormZipIf formZip;

    @Autowired      //ビジネスロジックをDI
    private BlZipIf blZip;

    /**
     * データモデルへのバインド
     */
    @ModelAttribute("FormZip")
    public FormZipIf setUpBindObject() {
        blZip.setForm(this.formZip);    //パラメータをビジネスロジックに継承
        return this.formZip;
    }

    /**
    * サンプル初期画面を表示する
    */
    @RequestMapping(value = "/zipview"  )
    public String zipview() {
            return "zip";
    }

    /**
    * 検索実行&結果画面を表示する
    */
    @RequestMapping(value = "/searchzip",   method = RequestMethod.POST )
    public String searchzip(
            @RequestBody String jParam          //JSON文字列(地域コード)がencodeされてくる
            ) throws Exception {

        //リクエストパラメータ(地域コード)がURLencodeされて来るのでdecodeする
        logger.log_info(this, "jParam["+jParam+"]");
        jParam = URLDecoder.decode(jParam,"UTF-8");
        logger.log_info(this, "jParam["+jParam+"]");

        //JSONリクエストフォーマット文字列をJavaオブジェクト(jsonReqArea)に変換
        jsonReqArea = (JsonReqAreaIf)jsonConvert.Deserialize(jParam, jsonReqArea);
        //リクエストパラメータクラスをフォームBeanに継承
        this.formZip.setJsonReqArea(jsonReqArea);

        //リクエストされた地域コードでDBを検索する
        blZip.getJPrefList();

        //検索結果をviewに表示する
        return "zipPref";
    }
}