Moatez Bouhdid Moatez Bouhdid - 3 months ago 10
AngularJS Question

AngularJs view with Spring : Not showing

So I have a simple application AngularJs and Spring mvc. I have a controlller that mapped to the angularJs page and I have this code in a jsp page :

<div ng-app="myApp" ng-controller="myCtrl">
<p>The name is <span ng-bind="person.lastName"></span></p>
{{ lastName }}
</div>

<script src="applications.js"></script>
<script src="controllers.js"></script>


application.js :

var app = angular.module("myApp", []);


controllers.js :

app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName= "Doe";
});


when I run this with Pivotal it dosn't run, but when I access the file directly within my browser it works like a charm, Someone care to explain pls ?

Thank you.
EDIT

WebConfig.java :

public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {

registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}

@Override
public void configureDefaultServletHandling ( DefaultServletHandlerConfigurer configurer )
{
configurer.enable();
}
}


resources folder :

Resources folder

The URL : http://localhost:8080/gestionprojet/Project/angularjs

My Controller :

@RequestMapping("/angularjs")
public String getAngularJs() {
return "AngularJs";
}

Answer

First of all, your files are under /WEB-INF/resources, but you have configured spring to load static resources from /resources. So they can't be served at all. The config should be

registry.addResourceHandler("/resources/**")
        .addResourceLocations("/WEB-INF/resources/");

The URL of your page is

/gestionprojet/Project/angularjs

Your page tries to load the script using the relative path

applications.js

So the corresponding absolute path where the browser looks for the JS files is

/gestionprojet/Project/applications.js

which doesn't match with the URLs you choose to serve static resources from. Assuming /gestionprojet is the context path of the application, the absolute URL should be

/gestionprojet/resources/applications.js

So the source code in the JSP should thus be

<script src="${pageContext.request.contextPath}/resources/applications.js"></script>
Comments