【问题标题】:Spring Web Mvc jQuery AJAX call with post not bidinding from with @ModelAttributeSpring Web Mvc jQuery AJAX 调用,post 不与 @ModelAttribute 绑定
【发布时间】:2018-05-29 00:48:35
【问题描述】:

我正在尝试将带有 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("editTile") 将其映射到对象。这是该课程的打印:

------------->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 错误,它甚至没有进行调用:

【问题讨论】:

    标签: java jquery ajax spring-mvc modelattribute


    【解决方案1】:

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

    尝试使用@RequestBody 而不是@ModelAttribute 作为Tile。

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

    【讨论】:

    • 你能给我举个例子吗?
    • @RequestMapping(value="/aURL",method=RequestMethod.POST, produces=MediaType.APPLICATION_JSON_UTF8_VALUE, consumes=MediaType.APPLICATION_JSON_UTF8_VALUE) public @ResponseBody ResponseEntity&lt;MyResponse&gt;doSomething( @RequestBody MyRequestModel requestModel) {
    猜你喜欢
    • 2017-11-27
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 2020-06-11
    • 1970-01-01
    • 2017-06-04
    • 2021-12-21
    相关资源
    最近更新 更多