簡體   English   中英

Spring Boot - 使用 ModelAndView 返回 ResponseEntity

[英]Spring Boot - Return ResponseEntity with ModelAndView

我在 Bootstrap Modal 中有一個 Thymeleaf 表單,我想用 jQuery - Ajax 調用來處理它。 表格如下所示:

<form th:action="@{/model/new}" th:method="POST" th:object="${modelForm}" id="form-new-model">
    <div class="form-group">
        <label for="name"><strong>Model name</strong></label>
        <input type="text" class="form-control" th:classappend="${#fields.hasErrors('name')} ? is-invalid : '' " th:field="*{name}" aria-describedby="name" placeholder="My awesome model">
        <div class="invalid-feedback" th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Error name</div>
    </div>
    <div class="form-group">
        <label for="description"><strong>Model description (optional)</strong></label>
        <textarea class="form-control" th:field="*{description}" rows="3" placeholder="Description"></textarea>
    </div>
    <div class="form-group row border-top align-items-center mb-0">
        <div class="col text-right mt-2">                              
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">Add</button>
        </div>
    </div>
</form>

在控制器中,我有以下內容:

@PostMapping("/model/new")
public String newModel(@Valid modelForm modelForm, BindingResult bindingResult, RedirectAttributes attributes) {

    if(bindingResult.hasErrors()){
        attributes.addFlashAttribute("org.springframework.validation.BindingResult.dexModelForm", bindingResult);
        attributes.addFlashAttribute("modelForm", modelForm);
        return "project/modal-new-model";
    }

    // creating the object since it is valid
    // and returning success response with the new updated view

    return "";
}

因此,由於我正在使用 jQuery 處理表單,因此我有:

$(document).on('submit', '#form-new-model', function(e){
    e.preventDefault();
    const csrf = $(this).find('input[name="_csrf"]').val();
    $.ajax({
        type: 'POST',
        url: '/model/new',
        headers: {'csrf-token':csrf},
        data: $(this).serializeArray(),
        cache: false,
        success: function(data){
            // Here the controller needs to bring me a Success Response (No error).
            // And then I refresh specific parts of the whole view.   
        },
        error: function(data){
            // I need first to bring 'SOMETHING' from the controller that says is an error.
            // Here I have to update the form since I will return a view from the controller. 
        }
    });
});

所以現在的問題是如何從控制器控制它是什么響應,並與響應一起發送特定的 HTML/Thymeleaf 視圖?

所以我用ModelAndView做了一個解決方案。

ModelAndView mv = new ModelAndView();
mv.setViewName("project/form-new-model");
mv.setStatus(HttpStatus.BAD_GATEWAY);
return mv;

使用狀態HttpStatus.BAD_GATEWAY可以在error響應中捕獲 jQuery 並且使用HttpStatus.OK進入 jQuery success

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM