求Java Spring MVC与Angular 4项目创建方法及示例项目结构
Hey there! I’ve built several projects using this stack, so I’ll walk you through the setup steps, typical project structures, and key tips to get you started smoothly.
Prerequisites
First, make sure you have these tools installed:
- For Spring MVC: JDK 8+, Maven/Gradle, an IDE (IntelliJ IDEA, Eclipse, or Spring Tool Suite)
- For Angular 4: Node.js 6.9.x+, npm 3.x+, Angular CLI 1.7.x (the last CLI version compatible with Angular 4)
1. Setting Up the Spring MVC Backend
Let’s use Maven for dependency management here.
Step 1: Create a Maven Project
In your IDE, generate a new Maven project using the webapp archetype (or Spring Initializr if you prefer a quicker setup, but the webapp archetype works for classic Spring MVC).
Step 2: Add Core Dependencies to pom.xml
Include Spring MVC, Servlet API, and JSON handling libraries:
<dependencies> <!-- Spring MVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.20.RELEASE</version> <!-- Stable for Angular 4 era --> </dependency> <!-- Servlet API --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- Jackson for JSON serialization --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.8</version> </dependency> </dependencies>
Step 3: Configure Spring MVC (Java-Based)
Skip XML config and use Java classes for cleaner setup:
Create WebConfig.java:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc @ComponentScan(basePackages = "com.yourproject") public class WebConfig extends WebMvcConfigurerAdapter { @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".jsp"); return resolver; } // Serve static files (like Angular build outputs later) @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**") .addResourceLocations("/static/"); } }
Create WebAppInitializer.java to replace web.xml:
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return null; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } }
Step 4: Build a Sample REST Controller
Add a test endpoint to verify the backend works:
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class ApiController { @GetMapping("/api/hello") public String getHelloMessage() { return "Hello from Spring MVC!"; } }
Step 5: Run the Backend
Deploy the project to a Tomcat 8.x server and test the endpoint at http://localhost:8080/api/hello.
2. Setting Up the Angular 4 Frontend
Step 1: Install Angular CLI for Angular 4
Angular 4 requires an older CLI version. Run this in your terminal:
npm install -g @angular/cli@1.7.4
Step 2: Generate a New Angular 4 Project
Create your frontend project with:
ng new my-angular4-frontend cd my-angular4-frontend
Step 3: Start the Dev Server
Launch the Angular development server:
ng serve
Access the app at http://localhost:4200.
Step 4: Add an API Service
Create a service to interact with the Spring backend:
ng generate service api
Update api.service.ts:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() export class ApiService { constructor(private http: HttpClient) { } fetchHelloMessage() { return this.http.get('http://localhost:8080/api/hello'); } }
Don’t forget to import HttpClientModule in app.module.ts:
import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ // ... other imports HttpClientModule ], providers: [ApiService], // ... }) export class AppModule { }
Step 5: Update a Component to Use the Service
Modify app.component.ts:
import { Component, OnInit } from '@angular/core'; import { ApiService } from './api.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { message: string; constructor(private apiService: ApiService) { } ngOnInit() { this.apiService.fetchHelloMessage().subscribe((data: string) => { this.message = data; }); } }
Update app.component.html:
<h1>{{ message }}</h1>
3. Typical Project Structure
Backend (Spring MVC)
src/ ├── main/ │ ├── java/ │ │ └── com/ │ │ └── yourproject/ │ │ ├── controller/ │ │ │ └── ApiController.java │ │ ├── service/ │ │ │ └── UserService.java │ │ ├── model/ │ │ │ └── User.java │ │ ├── WebConfig.java │ │ └── WebAppInitializer.java │ ├── resources/ │ │ └── application.properties (optional, for Spring Boot variants) │ └── webapp/ │ ├── static/ (holds Angular build files in production) │ └── WEB-INF/ │ └── views/ (for server-side JSP views, if needed) └── test/ └── java/ └── com/ └── yourproject/ └── controller/ └── ApiControllerTest.java pom.xml
Frontend (Angular 4)
my-angular4-frontend/ ├── src/ │ ├── app/ │ │ ├── components/ │ │ │ └── home/ │ │ │ ├── home.component.ts │ │ │ ├── home.component.html │ │ │ └── home.component.css │ │ ├── services/ │ │ │ └── api.service.ts │ │ ├── app.module.ts │ │ ├── app.component.ts │ │ └── app-routing.module.ts (for client-side routing) │ ├── assets/ │ │ ├── images/ │ │ └── styles/ │ └── index.html ├── angular-cli.json ├── package.json └── tsconfig.json
4. Key Integration Tips
- CORS Configuration: Since Angular runs on port 4200 and Spring on 8080, enable CORS in
WebConfig:@Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("http://localhost:4200") .allowedMethods("GET", "POST", "PUT", "DELETE"); } - Production Deployment: Build the Angular app with
ng build --prod, then copy thedistfolder contents into Spring’swebapp/staticdirectory. Spring will serve the Angular files as static resources. - Error Handling: Add global exception handlers in Spring (using
@ExceptionHandler) and Angular (usingHttpInterceptor) to manage errors gracefully.
内容的提问来源于stack exchange,提问作者Srikanth Pragallapati

