I am a beginner for Spring MVC. I want to use AngularJS and Spring MVC to setup a RESTful Single Page Application.
As a normal web app, when user request a URI, the backend web server will first transfer HTML template to front end and then use JSON to communicate.
I just wonder how HTML template are transferred to front end from Spring MVC service.
Any information will be appreciated. Thanks a lot.
Alternatively, and imho more sutiable to your requirements don't bother with the initial controller, and just serve your html and javascript as static resources , using something like this in your spring conf :
<mvc:resources location="/app/" mapping="/app/**"/>
<mvc:annotation-driven/>
And then only interact with backend using ajax and rest controllers.
A very simple example (taken from the Spring Guide Consuming a RESTful Web Service with AngularJS ) is the following:
Create an html page that is accessible statically (using Spring Boot as is done in the guide means that there a few standard places that will automatically be used for static resourses - if you don't use Spring Boot you will have to configure this), like:
<!doctype html>
<html ng-app>
<head>
<title>Hello AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="hello.js"></script>
</head>
<body>
<div ng-controller="Hello">
<p>The ID is {{greeting.id}}</p>
<p>The content is {{greeting.message}}</p>
</div>
</body>
</html>
The hello.js
script could be
function Hello($scope, $http) {
$http.get('http://yourpath/greeting').
success(function(data) {
$scope.greeting = data;
});
}
And then the corresponding Spring Service would be:
@RestController
public class Controller {
@RequestMapping("/greeting")
public Greeting greeting() {
return new Greeting();
}
}
public class Greeting {
private final Integer id;
private final String message;
public Greeting() {
this(1,"test")
}
public Greeting(Integer id, String message) {
this.id = id;
this.message = message;
}
public Integer getId() {
return id;
}
public String getMessage() {
return message;
}
}
In this very simple example, the template was transfered to the front-end simply because it was accessible as a static resource. You could of course imagine a more complex scenario where the controller would be something like
@Controller
public class Controller {
@RequestMapping("/greeting")
public ModelAndView greeting() {
return new ModelAndView("someView", someObject);
}
}
and Spring MVC would map someView
to a template based on the configured ViewResolver
. That way the template is dynamically populated by the server with whatever data is needed.
You can take a look at some more tutorials:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.