How to deploy AngularJS app and Spring Restful API

2019-02-01 18:58发布

问题:

I'm new to Spring and AngularJS. I followed the steps here to build the back end restful API, and it sends Json upon requests. So, according to the guide, When I run "mvn spring-boot:run" the tomcat server starts at localhost:8080.

Then I used Yeoman angular generator to build my angular app. And when I run "grunt serve" inside my angular app, the front end app runs at localhost:9000.

What should I do so that my angular app can be served together with my Springboot tomcat server on the same domain, say, localhost:8080 ?

Is there a sample project that I can follow? I found the following projects, but still cannot make it work as I don't have much background on tomcat.

  1. https://github.com/robharrop/spring-angularjs
  2. https://github.com/GermanoGiudici/angularjs-maven-tomcat-seed
  3. https://github.com/xvitcoder/spring-mvc-angularjs

回答1:

You need to take either:

  • the built files (grunt build then basically everything in the dist/ directory)
  • the raw files (your index.html and all JS as-is)

and copy them into one of the following folders (I recommend /public/): http://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot

Spring Boot will automatically add static web resources located within any of the following directories:

/META-INF/resources/

/resources/

/static/

/public/

This means that not only does Spring Boot offer a simple approach to building Java or Groovy apps, you can also use it to easily deploy client-side JavaScript code and test it within a real web server environment!

This is going to be a pain for development however since you will have to re-copy the files every time you make a change for the front end. For production your goal should be to deploy a versioned copy of the built files with your spring app.

For development you might want to consider letting grunt serve the Angular content and running both Tomcat and your grunt server (is it node?) and enabling cross origin requests between your front end and back end. OR you could just copy the whole angular directory into one of the above directories but that is a short term approach.