当前位置: 首页 > 知识库问答 >
问题:

spring Web Mvc jQuery AJAX调用with post not bidinding from with@modelAttribute

晁开宇
2023-03-14

我正在尝试用jquery向一个spring web mvc应用程序发送一个AJAX调用。我有一个模态,它包含一个形式:

<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注释,我更改了update方法的代码

@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
        });

共有1个答案

缪茂勋
2023-03-14

您似乎在发布一个来自Ajax的JSON(content-type:application/JSON)。

尝试使用@requestbody代替@modelattribute作为平铺。

表单post通常以content-type:application/www-form-url-encoded的形式发布。

 类似资料:
  • 问题内容: 我正在开发一个需要与Video4Linux抽象交互的应用程序。该应用程序使用mono框架以C#开发。 我面临的问题是我无法P /调用系统调用。或者,更准确地说,我可以P /调用它,但是它崩溃严重。 extern声明如下: 到目前为止,一切都很好。 使用的实际例程如下: 以上所有代码似乎都不错。该类用于按照标头规范计算I / O请求代码(基本上,它遵循处声明的宏)。 该参数是一个结构,声

  • 我们正在尝试开发一个自调用的lambda来成批处理S3文件。lambda角色具有附加调用所需的策略。 以下是自调用lambda的代码: 其中是对同一个lambda的调用调用。其余的事情都按预期工作,只要调用堆栈出现在这个调用请求上,它就会超时: 这是记录到CloudWatch的堆栈跟踪:

  • 主要内容:1.概述,2. 消费者调用服务,3. 提供者提供服务1.概述 在 dubbo:// 协议的调用,一共分成三种: sync 同步调用 async 异步调用 oneway 单向调用 前两种比较好理解,都是基于 Request Response 模型,差异点在异步调用,服务消费者不阻塞等待结果,而是通过回调的方式,处理服务提供者返回的结果。 最后一种,基于 Message 模型,发起调用,而不关注等待和关注执行结果。 因此,从性能上:oneway > a

  • 通过io的requestAbs方法调用/调用/使用REST API的vertx实现。vertx。果心http。vertx-core-3.2.0中的HttpClient类。jar导致HTTP错误::302,响应数据为HTML Erro响应。 不确定requestAbs方法的行为,因为没有引发异常,也没有写入任何日志。此外,还随附了使用vertx JAR的此方法的源代码。如果方法实现有bug,是否有问

  • 如果我在我的应用程序中导航并使用HomeButton返回Android LaunchScreen,则会调用OnSpt()挂钩,这很好。如果我使用Android TaskManager导航回应用程序,则会调用OnResume()。如果我使用Hardware BackButton在我的应用程序中导航,那么也会调用OnSpt(),这很好,但如果我导航回我的应用程序,则会调用Mainactive中的OnC

  • 问题内容: 您何时在Java中调用super()?我在派生类的某些构造函数中看到了它,但是不是每个父类的构造函数都会自动调用吗?为什么需要使用超级? 问题答案: 如果您提供这样的课程: 或这个: 编译器将为此生成代码: 因此,严格来说,对“ super()”的调用始终存在。 在实践中,您仅应在要传递给父构造函数的参数处调用“ super(…)”。 调用“ super()”(没有参数)并没有错,但是

  • 一般来说,使用Unity引擎开发的项目中,其内存分配主要由三部分组成:程序代码、托管堆(Managed Heap)以及本机堆(Native Heap)。其中,对于目前绝大多数基于Unity引擎开发的项目而言,其托管堆是由Mono分配和管理的。“托管” 的本意是Mono可以自动地改变堆的大小来适应你所需要的内存,并且适时地调用垃圾回收(Garbage Collection)操作来释放已经不需要的内存

  • 与以往版本不同的是,SDK 不再内置具体 API 的逻辑,所有的 API 均交由开发者自行调用,以获取用户列表为例: $api = $app->getClient(); 两种调用方式 当前版本准备了两种调用方式:原始方式调用 和 链式调用,请根据你的喜好自行选择使用方式,效果一致。 方式一:原始方式调用 $response = $api->post('/cgi-bin/user/info/upd