简体   繁体   English

Spring WebFlux - 在视图中使用 REST 填充新实体的 ID

[英]Spring WebFlux - Populate Id of new entity in using REST on view

My question is somewhat related to this question (but I am using WebFlux) - spring entity : return id of created record我的问题与这个问题有些相关(但我使用的是 WebFlux) - spring entity : return id of created record

My Entity:我的实体:

    @Table
    public class Todo {
        @Id
        private Long id;
        private String text;
        private boolean completed;
        ...Getters Setters...
    }

My Repository (Reactive):我的存储库(反应式):

public interface TodoRepository extends ReactiveCrudRepository<Todo, Long> {

    Flux<Todo> findAll();
    
    Flux<Todo> findByText(String text);
    
}

I have a Spring WebFlux's RestController like below:我有一个 Spring WebFlux 的 RestController,如下所示:

@RestController
@RequestMapping("/api")
class TodoController { 
private TodoRepository repository;
......   
@PostMapping("/todo")
        Mono<Todo> addTodo(@RequestBody Todo todo) {
            logger.info("Creating New Todo...");
            return repository.save(todo).log();
            //return repository.save(todo);
        }
}

On the view in JS (responsible for POSTing), I have the following:在 JS 中的视图(负责发布),我有以下内容:

    function insertNewRecord(formData) {
    fetch('/api/todo', {
        method: 'POST',
        headers: {
            'Accept': 'application/json, text/plain, */*',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ id: formData.todoid, text: formData.todotext, completed: formData.todocompleted })
    }).then((response) => {
        if (response.status >= 400 && response.status < 600) {
            throw new Error("Bad response from server");
        }
        if (response.status === 200) {
            alert('Entry Successful.. ! \nTable will be reloaded now.!');
            //reloadRecords();
            var table = document.getElementById("dataTable").getElementsByTagName('tbody')[0];
            var newRow = table.insertRow(table.length);
            
            // WHAT SHOULD I DO IN PLACE OF BELOW TWO LINES TO GET ID OF NEW ENTITY?

            cell1 = newRow.insertCell(0);
            cell1.innerHTML = formData.todoid;

            cell2 = newRow.insertCell(1);
            cell2.innerHTML = formData.todotext;
            cell3 = newRow.insertCell(2);
            cell3.innerHTML = formData.todocompleted;
            cell4 = newRow.insertCell(3);
            cell4.innerHTML = `<a class="btn btn-sm btn-warning mr-3" onClick="onEdit(this)">Edit</a>
                       <a class="btn btn-sm btn-danger" onClick="onDelete(this)">X</a>`;



        }
        // alert(response.status);
    })
        .catch((error) => {
            // Your error is here!
            alert(error)
        });
}

Using above post request from JS ( here , line # 20-56), the new entry is saved in the backend successfully.使用上面来自 JS 的 post 请求( 这里,第 20-56 行),新条目成功保存在后端。 No issues here at all till this point.到目前为止,这里根本没有问题。

My Form and table on the Thymeleaf template:我在 Thymeleaf 模板上的表格和表格:

<form onsubmit="event.preventDefault();onFormSubmit();"
            autocomplete="off">
            <div class="row mb-2">
                <div class="col-md-2 text-right font-weight-bold">
                    <label for="todoid" class="form-label">Id</label>
                </div>
                <div class="col-md-2">
                    <div class="input-group">
                        <input type="text" class="form-control form-control-sm"
                            name="todoid" id="todoid" readonly>
                    </div>
                </div>
            </div>


            <div class="row mb-2">
                <div class="col-md-2 text-right font-weight-bold">
                    <label for="todotext" class="form-label">Description</label>
                </div>
                <div class="col-md-6">
                    <div class="input-group">
                        <input type="text" class="form-control form-control-sm"
                            name="todotext" id="todotext">
                    </div>
                </div>
            </div>

            <div class="row mb-2">
                <div class="col-md-2 text-right font-weight-bold">
                    <label for="todocompleted" class="form-label">Completed?</label>
                </div>
                <div class="col-md-2">
                    <div class="input-group">
                        <select class="form-select form-control-sm" name="todocompleted"
                            id="todocompleted">
                            <option value="true">True</option>
                            <option selected value="false">False</option>
                        </select>
                    </div>
                </div>
            </div>


            <div class="row mt-3 mb-3">
                <div class="col-md-2 font-weight-bold"></div>
                <div class="col-md-9">
                    <input type="submit" value="Submit"
                        class="btn btn-sm btn-primary btn-block">
                </div>
            </div>

        </form>
    <div class="row mt-3 mb-3">
        <div class="col-md-2 font-weight-bold"></div>
        <div class="col-md-9">
            <table class="table table-sm table-striped" id="dataTable">
                <thead>
                    <tr>
                        <th>Id</th>
                        <th>Description</th>
                        <th>Completed?</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody id="appDataTable2"></tbody>
            </table>
        </div>
    </div>

Now, the html table is populated without the Id of the new entity/entry like this:现在,html 表中没有新实体/条目的 Id,如下所示:

在此处输入图片说明

But this is what I expect to happen.但这是我期望发生的事情。 ie populate the newly generated id too with the same request.即也用相同的请求填充新生成的 id。 Ie without reloading the entire list/table or refreshing the page:即无需重新加载整个列表/表格或刷新页面:

在此处输入图片说明

I am lost here.我在这里迷路了。 Any relevant example's link or clue on this will be greatly appreciated.任何相关示例的链接或线索将不胜感激。

your problem is quite simple you are using the object formData to populate your table, which is the data that is input in your html-form.你的问题很简单,你使用对象formData来填充你的表格,这是在你的 html 表单中输入的数据。

You have to use the returned data from the backend.您必须使用从后端返回的数据。

So this line doesnt work cell1.innerHTML = formData.todoid;所以这一行不起作用cell1.innerHTML = formData.todoid; , there is no value in the id field, because that data is set by the backend. ,id 字段中没有值,因为该数据是由后端设置的。

fetch('https://foobar.com', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(someData),
})
.then(response => response.json()) // extract json from response
.then(data => {
  
   ...

   cell1.innerHTML = data.id;   // use the returned data

   ...
})

This is the reason we need to see the entire codebase.这就是我们需要查看整个代码库的原因。 Because this part of code was never posted by you in the first place.因为这部分代码一开始就不是你贴出来的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM