Spring MVC angularjs example

ghz 10months ago ⋅ 142 views

Sure, I'll provide a basic example of integrating Spring MVC with AngularJS.

First, let's set up a simple Spring MVC controller to serve the HTML page containing AngularJS code:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class MainController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index() {
        return "index"; // This will return index.html located in src/main/resources/templates
    }
}

Next, let's create an index.html file in src/main/resources/templates directory:

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title>Spring MVC + AngularJS Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <script src="app.js"></script>
</head>
<body>

<div ng-controller="MyController">
    <h1>{{ message }}</h1>
</div>

</body>
</html>

In the index.html file, we include the AngularJS library from a CDN and link our own AngularJS application code located in app.js.

Now, let's create the app.js file in the same directory as index.html:

angular.module('myApp', [])
    .controller('MyController', function($scope, $http) {
        $scope.message = "Hello from AngularJS!";

        // You can make HTTP requests here using $http service
        // Example:
        // $http.get('/api/data').then(function(response) {
        //     $scope.data = response.data;
        // });
    });

In this example, we define an AngularJS module myApp and create a controller MyController inside it. We inject the $scope and $http services into the controller.

Finally, make sure your Spring Boot application is properly configured to serve static resources from the src/main/resources/static directory. This is where you should place your index.html and app.js files.

With this setup, when you run your Spring Boot application and navigate to http://localhost:8080/, you should see the message "Hello from AngularJS!" displayed on the page, indicating that AngularJS is working correctly.