Spring Web Mvc jQuery AJAX调用,使用@ModelAttribute进行postding而非bidinding

时间:2017-12-14 20:39:39

标签: java jquery ajax spring-mvc modelattribute

我正在尝试将jquery的AJAX调用发送到spring web mvc应用程序。我有一个包含表格的模态:

<div id="editTileModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true" style="display: none;">
<div class="modal-dialog modal-lg">
    <form id="frmEditTileModal" modelAttribute="editTile" class="floating-labels " action="/DESSOApplicationPortalAdmin/rest/tile/002" method="POST">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h4 class="modal-title" id="myLargeModalLabel">Edit Tile</h4>
        </div>
        <div class="modal-body">

            <div class="row">

                    <div class="col-md-6" >


                        <div class="form-group m-b-40 margin-top-20">
                            <input type="text" class="form-control" id="editTileId" name="id" required><span class="highlight"></span> <span class="bar"></span>
                            <label for="editTileId">Id</label>
                        </div>
                        <div class="form-group m-b-40">
                            <input type="text" class="form-control" id="editTileDescription" name="description" required><span class="highlight"></span> <span class="bar"></span>
                            <label for="editTileDescription">Description</label>
                        </div>
                        <div class="form-group m-b-40">
                            <input type="text" class="form-control" id="editTileRole" name="role" required><span class="highlight"></span> <span class="bar"></span>
                            <label for="editTileRole">Role</label>
                        </div>
                    </div>
                    <div class="col-md-6" >
                        <div class="form-group m-b-40 margin-top-20">
                            <input type="text" class="form-control" id="editTileTarget" name="target" required><span class="highlight"></span> <span class="bar"></span>
                            <label for="editTileTarget">Target</label>
                        </div>
                        <div class="form-group m-b-40">
                            <input type="text" class="form-control" id="editTileIndex" name="index" required><span class="highlight"></span> <span class="bar"></span>
                            <label for="editTileIndex">Index</label>
                        </div>
                        <div class="form-group m-b-40">
                            <input type="text" class="form-control" id="editTileTileimagename" name="tileImageName" required><span class="highlight"></span> <span class="bar"></span>
                            <label for="editTileTileimagename">Tile Image Name</label>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <div class="form-group m-b-40">
                            <input type="text" class="form-control" id="editTileUrl" name="url" required><span class="highlight"></span> <span class="bar"></span>
                            <label for="editTileUrl">Url</label>
                        </div>
                    </div>

                    <div class="col-md-12">                           
                        <div class="form-group m-b-40 form-check">
                            <label class="custom-control custom-checkbox">
                                <input type="checkbox" class="custom-control-input">
                                <span class="custom-control-indicator"></span>
                                <span class="custom-control-description">Disable Tile</span>
                            </label>
                        </div>
                    </div>

                    <div class="row>">
                        <div class="col-sm-6 col-md-6 col-xs-12">
                            <div class="white-box">
                                <h3 class="box-title">Tile Image Normal</h3>
                                <label for="img-tile-normal">You can add a default value</label>
                                <input type="file" id="img-tile-normal" class="dropify" data-default-file="resources/vendor/plugins/bower_components/dropify/src/images/test-image-1.jpg" />
                            </div>
                        </div>
                        <div class="col-sm-6 col-md-6 col-xs-12">
                            <div class="white-box">
                                <h3 class="box-title">Tile Image on Hover</h3>
                                <label for="img-tile-on-hover">You can add a default value</label>
                                <input type="file" id="img-tile-on-hover" class="dropify" data-default-file="resources/vendor/plugins/bower_components/dropify/src/images/test-image-1.jpg" />
                            </div>
                        </div>
                    </div>



            </div>
        </div>

        <div class="modal-footer">
            <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Close</button>
            <button id="btnSaveEditTile" type="submit" class="btn btn-danger waves-effect waves-light">Save changes</button>
        </div>
    </div>
    </form> 
    <!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->

这是jQuery

       $('#frmEditTileModal').submit(function (e) {
        e.preventDefault();
        alert("save edit start!");

        var editSuccesFunc = function () {
            alert('Success Edit!');
        };
        var editErrorFunc = function () {
            alert('Error Edit!');
        };

        var tileId = $('#editTileId').val();
        alert("data to send: " + $('#editTileId').val());

        var formData = new FormData();
        formData.append("id", $('#editTileId').val());
        formData.append("description", $('#editTileDescription').val());
        formData.append("role", $('#editTileRole').val());

        $.ajax({
            type: "POST",
            url: "/DESSOApplicationPortalAdmin/rest/tile/" + tileId,
            data: $('#frmEditTileModal').serialize(),
            contentType: "application/json",
            dataType: "json",
            success: editSuccesFunc,
            error: editErrorFunc
        });
    });

这是java控制器:

    @RestController
    @RequestMapping(value = "rest/tile")
public class TileRestController {

    @Autowired
     TileService tileService;

    @RequestMapping(value = "/{tileId}", method = RequestMethod.GET)
       public Tile getProductById(@PathVariable(value = "tileId") String tileId) {
        System.out.println("------------->" + this.getClass().getSimpleName() + ": getProductById called. Searching for Tile Id " + tileId);
        return tileService.getTileById(tileId);
    }

    @RequestMapping(value = "/{tileId}", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public  Tile update( @ModelAttribute("editTile") Tile tile, @PathVariable(value = "tileId") String tileId) {
        Tile updatedTile = new Tile();
        //updatedTile.setId("099");
        //updatedTile.setDescription("ExampleTile");

        System.out.println("------------->" + this.getClass().getSimpleName() + " update method: print object fields: "+tile.toString());
        return updatedTile;
       //return tileService.updateTile(tile);

    }
}

当我尝试正常提交(没有ajax或jquery)时,控制器正确地读取对象的字段。

但是,当我尝试像ajax调用一样时,它会正确发送数据,但控制器不会通过modelAttribute将其映射到对象(&#34; editTile&#34;)。这是班级的印刷品:

  

-------------&gt; TileRestController更新方法:打印对象字段:Tile {tileImageName = null,description = null,role = null,url = null,target = null,index = 0,id = null,disabled = false}

我错过了什么吗?

编辑: 我在答案中尝试了一个建议,但它似乎没有用。这是我做的:

我更改了更新方法的代码,以便使用@RequestBody注释

@RequestMapping(value = "/{tileId}", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public  Tile update( @RequestBody Tile tile, @PathVariable(value = "tileId") String tileId) {
    Tile updatedTile = new Tile();
    //updatedTile.setId("099");
    //updatedTile.setDescription("ExampleTile");

    System.out.println("------------->" + this.getClass().getSimpleName() + " update method: print object fields: "+tile.toString());
    return updatedTile;
   //return tileService.updateTile(tile);

}

另外,我改变了我的内容类型以及ajax调用:

$.ajax({
            type: "POST",
            url: "/DESSOApplicationPortalAdmin/rest/tile/" + tileId,
            data: $('#frmEditTileModal').serialize(),
            contentType: "application/www-form-url-encoded",
            dataType: "json",
            success: editSuccesFunc,
            error: editErrorFunc
        });

然而,现在我得到一个ajax错误,它甚至没有拨打电话: enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

您似乎是从ajax发布JSON(内容类型:application / json)。

尝试使用@RequestBody代替@ModelAttribute作为平铺。

FORM帖子通常会被发布为内容类型:application / www-form-url-encoded。