首页 > 解决方案 > Spring控制器不加载视图

问题描述

我使用 ajax 通过按钮单击调用控制器。我希望它加载 hello.html 页面,但我希望 spring 执行它而不是 ajax。

单击按钮后会发生什么,但我确定控制器正在被击中。

这是我使用 ajax 通过按钮单击调用的控制器。

    @RequestMapping(value="/submitName", method=RequestMethod.GET)
    public String submitName(@RequestParam String name, Model model) {
        System.out.println(name);
        model.addAttribute("name", name);
        return "hello";
    }

这是ajax调用。

$('#submit-button').on('click', function() {
    $.ajax({
        type: 'GET',
        url: '/submitName',
        data: {name: $('#name').val()}
    });
});

有趣的是在 chrome 网络选项卡中,它显示了我期望的页面。这是一个片段。

标签: springspring-bootspring-mvc

解决方案


AJAX 调用只是将请求发送到服务器(控制器)并收到响应,

默认情况下,它不负责重新加载页面。

这就是为什么当您单击按钮时它会点击服务器端但停留在同一页面上。

很简单,有两种方法可以加载新页面( hello.html )

1| 使用 AJAX 调用:

在按钮单击方法上,您必须显式加载页面(Ajax Success 块中的最佳实践)

添加此窗口加载metbod:
window.location.href =“ http://localhost:8080/hello.html ”;

 Like: 

 $('#submit-button').on('click', function() {
 $.ajax({
    type: 'GET',
    url: '/submitName',
    data: {name: $('#name').val()}
    window.location.href = "http://localhost:8080/hello.html";
  });
 });

2| 按钮上的直接 Http 调用

HTML

  <a class="btn btn-primary btn-lg pull-right" href="http://localhost:8080/hello" role="button">Hello Page</a>

JSP:

 <a class="btn btn-primary btn-lg pull-right" href="${pageContext.request.contextPath}/hello" role="button">Hello page</a>

百里香叶

<a class="btn btn-xs" th:href="@{/hello})}">Hello Page </a>

推荐阅读