2

I want to make a simple web project using angular 4 and spring mvc. I am wondering that how can i integrate angular 4 with spring mvc that runs on a same server. Right now i running spring in localhost:8080 and angular in localhost:4200.

I did a lot research on it but cann't find any proper solution yet.

Spring-Project Structure

Spring- Project Structure

Angular - Project Structure

enter image description here

Is that possible to run angular and spring mvc project on a same server??

1 Answer 1

5

I believe best practice is to have two separate projects. That said, here's how we've incorporated an angular project into our Spring MVC project.

  1. Renamed src folder in our angular project to ng-src.
  2. Copied the contents of the angular project, not the folder itself, into our Spring MVC project. This added e2e, node_modules, and ng-src and several files to the root of our Spring MVC project.
  3. Renamed index.html in ng-src to index.jsp
  4. Edit a few things in .angular-cli.json

    "root": "ng-src",
    "outDir": "src/main/webapp/app",
    

    and

    "index": "index.jsp",
    
  5. If DispatcherServlet is mapped to /, add a resource mapping to spring config In XML:

    <mvc:resources mapping="/app/**" location = "/app/"/>
    

    Java Config:

    public void addResourceHandlers(ResourceHandlerRegistry registry) {
         registry.addResourceHandler("/app/**")
                .addResourceLocations("/app/")
    }
    
  6. As we develop, we have a process running in the background building angular:

    ng build --bh "${pageContext.request.contextPath}/app/" --w
    

    The --bh sets the baseHref used in generating index.jsp. --w tells angular-cli to watch the directory and build anytime things change.

Any changes made to the angular project are made under ng-src. Angular-cli will see those changes and build the project. Your angular project is built to /your-context-path/app/

Our IDE watches the project for changes on the filesystem. Depending on your IDE, you may need to configure it to watch. I know eclipse doesn't by default.

You'll need to refresh the page in your browser to see changes (ctrl+F5).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.