如何在Spring Boot中使用ajax(jQuery)来使用REST服务?

时间:2017-09-10 18:13:54

标签: jquery json ajax rest spring-boot

我正在关注此主题https://spring.io/guides/gs/consuming-rest-jquery/#_create_the_application_page

的官方Spring文档

也许还有其他遗漏/丢失的东西,但我不能让它与我合作(Intellij,SpringBoot)。

我有完全相同的问候语(来自他们的repo https://github.com/spring-guides/gs-rest-service/tree/master/complete/src/main/java/hello),GreetingController类,后者应该返回JSON数据。分开测试的两个控制器都运行良好。我的“index.html”和“hello.js”也被复制到一个发球台。

但据我了解,要使其正常工作,需要将客户端重定向到此“index.html”页面,因此为此我添加了另一个Controller。

最后,完整的项目结构:

src
|--main
   |---java
       |---com.example.demo
           |---controller
               GreetingController.java
               ClientController.java
           |---model
               Greeting.java
       DemoApplication.java
  |---resources
      |---static.js
             hello.js
      |---templates
             index.html
      application.properties

hello.js读作:

$(document).ready(function() {
$.ajax({
    url: 'https://localhost:8080/greeting'
}).then(function(data) {
    $('.greeting-id').append(data.id);
    $('.greeting-content').append(data.content);
});

});

的index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Hello jQuery</title>

    <!--alt+enter to download the library in case it's not there-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="../static/hello.js"></script>
</head>

<body>
<div>
    <p class="greeting-id">The ID is </p>
    <p class="greeting-content">The content is </p>
</div>
</body>
</html>

如您所见,hello.js具有以下功能:

url: 'https://localhost:8080/greeting'

据我所知,这应该是访问这个地址,收到的响应将由GreetingController提供,然后解析为JSON对象。但我只得到:

ID为
内容是

怎么了?与本教程的唯一区别是我有自己常用的Spring Controller而不是他们的Groovy。还需要什么才能将它们全部粘合在一起?

1 个答案:

答案 0 :(得分:1)

在评论中澄清说找不到javascript文件。要修复你必须

  1. 将脚本位置更改为<script src="hello.js"></script>,因为Spring引导在src / main / resources / static下默认查找静态文件
  2. 此外,网址必须是http而不是https。