嗨,我正在尝试入门指南中给出spring.io示例。
它没有显示任何错误,但是当我在浏览器中打开链接http://localhost:8070/testJson时,我没有得到HTML视图,它显示的只是这样的Json输出
{"id":1,"content":"Hello World !"}
但我想让它显示一个正确的HTML视图,我不能在这里使用@Controller,我想使用Jquery javascript显示HTML,我该怎么做?
这是我的控制器方法
@RestController
public class MyRestController {
private final Long counter = 1l;
@GetMapping("/testJson")
public TestJsonDto getTestJson(){
TestJsonDto testJsonDto=new TestJsonDto(counter,
"Hello World !");
return testJsonDto;
}
}
这是我的数据类
public class TestJsonDto {
private Long id;
private String content;
public TestJsonDto(Long id, String content) {
this.id = id;
this.content = content;
}
public TestJsonDto() {
}
/*
GETTERS AND SETTERS WILL GO HERE
*/
下面是我的应用程序类
@SpringBootApplication
@EnableJpaRepositories
public class MyjarApplication {
public static void main(String[] args) {
SpringApplication.run(MyjarApplication .class, args);
}
}
我的Html文件是
<!DOCTYPE html>
<html>
<head>
<title>Hello jQuery</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script src="/my.js"></script>
</head>
<body>
<div>
<p class="greeting-id">The ID is </p>
<p class="greeting-content">The content is </p>
</div>
</body>
</html>
最后,这是我的javascript
$(document).ready(function() {
$.ajax({
url: "http://localhost:8070/testJson"
}).then(function(testJsonDto) {
$('.greeting-id').append(testJsonDto.id);
$('.greeting-content').append(testJsonDto.content);
});
});
我的application.properties在这里
server.port=8070
my.js的位置在src/main/resources/static/my . js下
如果要添加可与 API 交互的前端,可以像这样构建应用:
此代码设置您的应用程序,包括静态资源,例如您的资源/静态/index.html
将呈现为根路径localhost:8090
除非您在任何控制器中连接此路径(确保root在任何其他@Controller或注释中不是隐式/显式用户)。
@SpringBootApplication
@EnableJpaRepositories
public class MyjarApplication {
public static void main(String[] args) {
SpringApplication.run(MyjarApplication .class, args);
}
}
因此,渲染所需HMTL的一种简单方法是将HTML放在resource/static/index.HTML
:
<!DOCTYPE html>
<html>
<head>
<title>Hello jQuery</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script src="/my.js"></script>
</head>
<body>
<div>
<p class="greeting-id">The ID is </p>
<p class="greeting-content">The content is </p>
</div>
</body>
</html>
JS应该放在资源/静态/我的.js
:
$(document).ready(function() {
$.ajax({
url: "http://localhost:8070/testJson"
}).then(function(testJsonDto) {
$('.greeting-id').append(testJsonDto.id);
$('.greeting-content').append(testJsonDto.content);
});
});
在你的rest控制器中,路径/testJson
将由getTestJson()
参与:
@RestController
public class MyRestController {
private final Long counter = 1l;
@GetMapping("/testJson")
public TestJsonDto getTestJson(){
TestJsonDto testJsonDto=new TestJsonDto(counter,
"Hello World !");
return testJsonDto;
}
}
因此,您访问localhost:8090以获取前端,并通过javascript访问localhost:8090/testJson以获取API。