Struts2のJSONを伴ったリクエストのデータマッピング
「JSONでリクエスト」はひっかかるんですが、「JSONで返す」って方法がなかなかのってなかったので。
画像uploadで試しにやってみたら出来ました。
●HTML
<form action="#" method="post" enctype="multipart/form-data"> <s:file name="itemImg" id="upload" label="File" /> </form>
●JS(jQuery使用)
$(function() { $('input#upload').change(function() { $(this).upload( 'json-request!tempImageUpload', function(res) { $("input#form_displayFileName").val(res.itemImgFileName) }, 'json'); }); });
●Action
@Results({ @Result(name = "upload", location = "upload-json.jsp") }) @Controller public class JsonRequestAction extends AbstractSupplierAction { /** アップロードファイル. */ private File itemImg; /** アップロードファイル コンテキストタイプ. */ private String itemImgContentType; /** アップロードファイル名. */ private String itemImgFileName; /** * 一時画像アップロード. * @return String */ public String tempImageUpload() { //なんかの処理 return "upload"; } //メンバのアクセサ。省略。 }
●JSP
<!-- [MEMO]戻りはJSONですが、content="text/html;を指定してないとFF等でダウンロードポップアップ出てしまうのでJSPでJSONにしています --> <%@ page contentType="text/html; charset=UTF-8" trimDirectiveWhitespaces="true" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> {"itemImgFileName":"<s:property value="itemImgFileName"/>"}
contentTypeにtext/html;を指定しないとFFとかでポップアップでちゃって受け取れなかったり。
なのでわざわざJSPで指定してあげて、実際に送る内容はJSONの記法にあわせてあげればできた。