Spring-Boot:重定向和刷新模型和页面

use*_*938 8 redirect spring spring-mvc thymeleaf

我有一个spring-boot应用程序,withemleaf.我反复更新页面,并将其重定向到同一页面,所以我希望页面的元素得到更新:

@GetMapping("/suggested-events/vote/{eventId}")         
public String voteForEvents(Model model,
                            @PathVariable("eventId") Long eventId,
                            @RequestParam(value = "message", required = false) String message ) {
    log.info("The message is: "+message);
    SuggestedEvent event = suggestedEventService.findSuggestedEventById(eventId);
    ArrayList<SuggestedEvent> events = suggestedEventService.findSuggestedEventsByArea(event.getArea());
    model.addAttribute("mainEvent",event);
    model.addAttribute("events",events);
    model.addAttribute("message",message);

    return "/suggested-event/vote";
}
Run Code Online (Sandbox Code Playgroud)

当按钮在视图中被按下时,它会触发以下post方法:

@PostMapping("/suggested-events/vote")
public String voteForASuggestedEvent(RedirectAttributes redirectAttributes){
    log.info("You have made a vote");
    redirectAttributes.addAttribute("message", "Success");

    return "redirect:/suggested-events/vote/1";
}
Run Code Online (Sandbox Code Playgroud)

该第二控制器方法执行a的操作message,并将其重定向到第一方法.因此,它成功重定向到第一个方法并记录

log.info("The message is: "+message);
Run Code Online (Sandbox Code Playgroud)

但它没有刷新我的页面,我没有得到消息作为模型

当我重定向到第一个方法时,我希望它添加message到我的模型:

model.addAttribute("message",message);
Run Code Online (Sandbox Code Playgroud)

但它没有添加到我的页面

Mik*_*ick 5

当在视图中按下按钮时,它会触发以下 post 方法:

听起来这个触发器使用的是 AJAX,而不是表单提交。这样做会符合您所描述的症状。

如果您POST使用/suggested-events/voteAJAX,服务器将返回302,浏览器将遵循它。但是,该 302 的响应仍然是 AJAX 调用的结果。您可以在成功回调中访问它,但浏览器不会为您呈现它。

但它不会刷新我的页面

如果 302 不会导致您的页面重新呈现,这也表明您正在使用 AJAX。

如果您实际上使用表单提交,浏览器使用成功重定向返回的标记重新呈现。

这可以通过使用以下两个按钮来验证vote.html

  <form action="http://localhost:8080/suggested-events/vote" method="POST">
    <input type="submit" text="Submit" />
  </form>

  <button onclick="postmessage();" >Button</button>

  <script>
    function postmessage() {
        $.ajax({
            method: 'POST',
            data: {},
            url: 'http://localhost:8080/suggested-events/vote'
        });
    }
  </script>
Run Code Online (Sandbox Code Playgroud)

第一个按钮将按预期工作,第二个按钮与您描述的症状相符。

如果您已经在使用表单,请用它更新问题(或者更好的是,更新整个 Thymeleaf 模板)。


Beq*_*uci 0

在Spring中有很多方法可以重定向页面,但请确保模型属性关闭消息是否正确传递到FrontEnd或将类似参数传递到另一个处理程序,您可以查看此文档:http ://javainsimpleway.com/spring-mvc-将模型属性从一个控制器重定向到其他控制器/,希望这有用!