Run Spring4MVC with Angular 2 on a single server

五迷三道 提交于 2019-11-28 04:25:15

No answers till now thats fine, I got solution. How I did ?

You need 2 contexts.

(1) Angular 2 project and

(2) Spring MVC

Follow below steps to achieve our main goal, to run SPRINGMVC + Angular2 on a single server.

  1. Create normal Dynamic web project.
  2. Add all dependancy required for spring or user maven pom.xml
  3. Open CMD, navigate to angular2 application. Hit command

    npm install and then

    ng build or use ng build --prod for production

this command will create a "dist" folder, copy all files including all folders.

  1. Paste those files and folders into WebContent directory.

  2. Last thing, you need to change basehref="./" in index.html. Now you are ready to run server or you can deploy war file and serve it with tomcat or other servers.

If you are using Rest webservices and want to run angular2 and spring in a single server,

You need to put webServiceEndPointUrl as per your host url. For example, If you are running app on localhost:8080, you need to keep url

webServiceEndPointUrl= "http://localhost:8080/api/user"; at angular side. After that you can build and copy paste to your WebContent folder.

See below Image, File structure for springMVC+ANGULAR2

I know there are many drawbacks to use these way for running application on a single server, but if it must required you can follow this.

If you change anything at angular side, you need to copy paste dist folder all time and then you can deploy it!

You can automate your solution - just use frontend-maven-plugin (with which you can install nodejs and build the angular project) and maven-resources-plugin to copy the contents of /angular/dist/ directory into root of .war file (see also this article)

<plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-resources-plugin</artifactId>
      <version>3.0.2</version>
      <executions>
        <execution>
          <id>default-copy-resources</id>
          <phase>process-resources</phase>
          <goals>
            <goal>copy-resources</goal>
          </goals>
          <configuration>
            <overwrite>true</overwrite>
            <outputDirectory>${project.build.directory}/${project.artifactId}-${project.version}/</outputDirectory>
            <resources>
              <resource>
                <directory>${project.basedir}/angular/dist</directory>
              </resource>
            </resources>
          </configuration>
        </execution>
      </executions>
</plugin>

And then you can use hot reload feature (while developing) on nodejs server, runned by ng serve with Angular CLI tool.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!