I have found a lot of examples that ask similar questions. However, most of the advice says to just use @Controller instead of @RestController when you want to use:
//@Controller
@RestController // @Controller and @ResponseBody into one
public class SreAppController {
@GetMapping("/")
public String index() {
return "index";
}
}
Since this just returns the String index and does not fetch the HTML file index.html. I know that @ResponseBody, which is in the @RestController tag, renders the output as is from this question. So, I found this tutorial which gives this code:
@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));
}
}
Which I would like to use with AngularJS and format using HTML. This tutorial shows how to consume a RESTful web service, but shows how to consume from http://rest-service.guides.spring.io/greeting. I tried putting localhost:8080/greeting in it's place, but that still just gives a 404 error for localhost:8080 and just returns json for localhost:8080/greeting.
How do I use @RestController with AngularJS and HTML in one application? The intention is to go to localhost:8080 and get the same output as this tutorial:
I know the json from localhost:8080/greeting is coming straight from the Rest controller. I am not sure why the angularJS controller is not found when using localhost:8080.
The tutorial states the need for a minimal amount of web application code so Spring Boot knows to start Tomcat. The suggest app.groovy (shown below) but my rest controller starts the embedded Tomcat server, so I don't think this is the issue.
app.groovy
@Controller class JsApp { }
Javascript and html for reference:
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>
Hierarchy of project


$http.get('localhost:8080/greeting')should be$http.get('http://localhost:8080/greeting'), or simply$http.get('/greeting'). Open your browser dev tools, and look at the requests you send in the network tab. Also, why use angularjs 1.4.3, and not the latest version?