使用@RestController和@GetMapping

时间:2018-06-28 19:24:17

标签: angularjs rest spring-boot

我发现了很多提出类似问题的例子。但是,大多数建议都建议在要使用时仅使用@Controller而不是@RestController:

//@Controller
@RestController // @Controller and @ResponseBody into one
public class SreAppController {
    @GetMapping("/")
    public String index() {
        return "index";
    }
}

因为这仅返回String索引,而不获取HTML文件index.html。我知道@RestController标记中的@ResponseBody可以按this问题原样呈现输出。因此,我发现this教程提供了以下代码:

@RestController
public class SreAppController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @GetMapping("/greeting")
    public Greeting index(@RequestParam(value="name", defaultValue="World") String name){
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }
}

我想与AngularJS一起使用,并使用HTML格式化。 This教程展示了如何使用RESTful Web服务,但展示了如何从http://rest-service.guides.spring.io/greeting中使用。我尝试将localhost:8080 / greeting放到该位置,但这仍然只为localhost:8080提供404错误,并且只为localhost:8080 / greeting返回json。

如何在一个应用程序中将@RestController与AngularJS和HTML结合使用?目的是转到localhost:8080并获得与本教程相同的输出:

enter image description here

我知道来自localhost:8080 / greeting的json直接来自Rest控制器。我不确定为什么在使用localhost:8080时找不到angularJS控制器。

本教程指出需要最少的Web应用程序代码,以便Spring Boot知道启动Tomcat。建议使用app.groovy(如下所示),但是我的rest控制器启动了嵌入式Tomcat服务器,因此我认为这不是问题。

app.groovy

@Controller class JsApp { }

JavaScript和html供参考:

app.js

"use strict";
angular.module('demo', []).controller('app', function($scope, $http) {
        $http.get('/greeting').
            then(function (response) {
            $scope.greeting = response.data;
    });
});

index.html

<!DOCTYPE html>
<html lang="en" ng-app="demo">
<head>
    <meta charset="UTF-8">
    <title>Hello AngularJS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
    <script src="app.js"></script>
</head>
<body>
    <div ng-controller="app">
        <p>The ID is {{greeting.id}}</p>
        <p>The content is {{greeting.content}}</p>
    </div>
</body>
</html>

项目层次结构

enter image description here

1 个答案:

答案 0 :(得分:2)

那么您打算做的是访问Spring Boot应用程序内部的AngularJS应用程序,但index.html不显示,提示吗?

那么您需要了解几件事:

1)您的AngularJS应用程序必须作为静态内容提供。

您可以在本教程中找到一些示例:Serving Static Web Content with Spring Boot

基本上,您的AngularJS应用必须放置在用于静态内容的特殊文件夹中的Spring Boot应用源代码中-有多个选项,但通常将其命名为/ public或/ static。

2)Spring Boot管理您的所有URL。

这意味着Spring Boot应用程序会拦截对您应用程序的所有请求,然后尝试将URL与所有现有@Controller进行匹配。

因此,如果您GET http://<your ip:port>/并且有一个@Controller映射根/GET,则该@Controller将响应请求,就像在第一个示例中您的SreAppController班。

但是,如果您不这样做,Spring Boot会尝试在每个特殊文件夹中查找静态内容,并为它提供服务。

请注意,您可以在控制器和静态Web导航中混合使用ULR ...!

希望我至少提供了一点帮助。 :-)