![](/img/trans.png)
[英]How to integrate an Angular 4 app with a Spring Boot stack?
[英]How to integrate angular with spring boot to see angular web interface on spring boot port?
我有使用 angular4 開發的后端 Spring Boot 應用程序和前端。 由於這兩個在部署時在不同的端口(8080,4200)上運行,因此不顯示任何 UI。 在本地,使用下面的啟動 angular 服務器在 localhost:4200 上工作絕對正常並顯示 Web 界面:
ng serve --proxy-config proxy.conf.json
其中 proxy.conf.json 有內容:
{
"*": {
"target": "http://localhost:8080",
"secure": false,
"logLevel": "debug"
}
}
但在嘗試與 springboot 應用程序(本地主機:8080)集成時則不然。 可能,它需要在部署之前烘焙 ng 業務邏輯(節點/npm 安裝等)。
所以我使用ng build
將生成的文件復制到輸出目錄 - src/main/resources/static ,現在它位於 spring-boot 應用程序路徑中。 啟動 tomcat 在 localhost:8080 上仍然沒有顯示任何 UI。 我確實在 chrome 選項卡上看到了 Angular 符號/圖標,但在 html 頁面上沒有顯示任何內容。
我還添加了一個控制器方法來返回 index.html,以便它可以在路徑中提供靜態文件。
@GetMapping("/")
public String index() {
return "forward:/index.html";
}
但是這樣做只會在網頁上顯示“forward:/index.html”字符串而不是 html 內容。 我是否需要更改此 index.html 中的某些內容,以便它可以路由到我創建的 ng 組件? 不知道更改 index.html 中的選擇器是否重要。 由於我的主要組件不是應用程序組件(默認情況下是根組件)而是登錄組件,因此在 index.html 中我將<app-root></app-root>
更改為登錄組件的選擇器<app-login></app-login>
; UI中仍然沒有顯示任何內容。
似乎 spring-boot 無法理解角度的東西以及如何路由到主要的 ng 組件。
下面是 index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello App</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
<script type="text/javascript" src="runtime.js"></script><script type="text/javascript" src="polyfills.js"></script><script type="text/javascript" src="styles.js"></script><script type="text/javascript" src="vendor.js"></script><script type="text/javascript" src="main.js"></script></body>
</html>
項目結構:
-src
-main
-java
- backend
- AppController
- AppService
- Main.java
- frontend
- src
- index.html
- app
-login
- login.component.html
- login.component.css
- login.component.ts
etc..
- resources
- static
- index.html
- application.properties
- ...
部署時如何讓前端與后端服務器一起工作? 我是否需要在 application.properties 中添加任何參數或配置,以便應用程序在啟動時從 /resources 提供靜態內容? 我是否添加任何 resourceLocationHandler 為其提供服務?
任何幫助,非常感謝!
請使用存檔實用程序打開 jar 文件,看看其中是否有靜態文件。 如果它們可用,您需要告訴 Spring 您在地址欄中輸入的 URL 實際上是 Angular 路由:
@Controller
public class Routing {
@RequestMapping({ "", "/login", "/products/**" })
public String gui() {
return "forward:/index.html";
}
}
您可以使用 maven 和frontend-maven-plugin 來完成
首先,我同意將前端與后端分開的事實
所以我會創建這個項目結構:
parentDirectory
- frontend
- angular src files
- pom.xml
- backend
- spring boot based backend
- pom.xml
- pom.xml
父pom.xml
將是:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>apringangular</artifactId>
<packaging>pom</packaging>
<name>Spring angular</name>
<modules>
<module>backend</module>
<module>frontend</module>
</modules>
</project>
前端 pom 將是:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>test</groupId>
<artifactId>springangular</artifactId>
<version>1.0</version>
</parent>
<artifactId>frontend</artifactId>
<packaging>jar</packaging>
<name>frontend</name>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<phase>initialize</phase>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>
<file>frontend_project_properties.properties</file>
</files>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<filesets>
<fileset>
<directory>dist</directory>
<includes>
<include>*</include>
</includes>
</fileset>
</filesets>
</configuration>
</plugin>
<plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>install node and npm</id>
<goals>
<goal>install-node-and-npm</goal>
</goals>
<configuration>
<nodeVersion>v8.11.3</nodeVersion>
<npmVersion>6.3.0</npmVersion>
<arguments>${http_proxy_config}</arguments>
<arguments>${https_proxy_config}</arguments>
<arguments>run build</arguments>
<npmInheritsProxyConfigFromMaven>false</npmInheritsProxyConfigFromMaven>
</configuration>
</execution>
<execution>
<id>npm install</id>
<goals>
<goal>npm</goal>
</goals>
<phase>generate-resources</phase>
<configuration>
<arguments>install</arguments>
</configuration>
</execution>
<execution>
<id>npm run build</id>
<goals>
<goal>npm</goal>
</goals>
<configuration>
<arguments>${http_proxy_config}</arguments>
<arguments>${https_proxy_config}</arguments>
<arguments>run build</arguments>
<npmInheritsProxyConfigFromMaven>false</npmInheritsProxyConfigFromMaven>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
在文件frontend_project_properties.properties
我有 node 和 npm 的代理配置。 像這樣的東西:
http_proxy_config=config set proxy http://USERNAME_PROXY:PASSWORD_PROXY@PROXY_HOST:PROXY_PORT
https_proxy_config=config set https-proxy http://USERNAME_PROXY:PASSWORD_PROXY@PROXY_HOST:PROXY_PORT
后端 pom 是經典的 Spring Boot 后端。 您必須告訴 maven 前端在哪里,以便 maven 能夠創建獨特的 Web 應用程序。 在后端 pom.xml 中,您應該添加如下內容:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>it.eng.tz.area.vasta.mev</groupId>
<artifactId>appmgr</artifactId>
<version>1.0</version>
</parent>
<artifactId>appmgrbackend</artifactId>
<packaging>war</packaging>
<name>Application manager backend</name>
<description>
Lato backend del sistema di gestione
</description>
<dependencies>
<!-- Your dependencies -->
</dependencies>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<excludes>
<exclude>**/*.*</exclude>
</excludes>
</testResource>
</testResources>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<webResources>
<resource>
<directory>../frontend/dist</directory>
</resource>
</webResources>
</configuration>
</plugin>
</plugins>
</build>
</project>
通過這種方式告訴maven-war-plugin
HTML 和靜態代碼位於前端項目的dist
目錄中 注意,在開發過程中,node.js 在 4200 端口上提供資源,而 spring 使用不同的端口。 因此,您將遇到跨站點問題。 通過使用 spring security yuo 可以解決這個問題 bu 配置,在后端,spring security 以這種方式:
@Configuration
@EnableWebSecurity
@Import(value= {AppMgrWebMvcConfig.class})
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled=true)
public class AppMgrWebSecConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("oauthUsrDetailSvc")
UserDetailsService userDetailsService;
@Autowired
@Qualifier("userPwdEnc")
private PasswordEncoder pwdEncoder;
@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
web.httpFirewall(this.allowUrlEncodedSlashHttpFirewall());
}
@Bean
public HttpFirewall allowUrlEncodedSlashHttpFirewall()
{
StrictHttpFirewall firewall = new StrictHttpFirewall();
firewall.setAllowUrlEncodedSlash(true);
firewall.setAllowSemicolon(true);
return firewall;
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
{
auth.userDetailsService(userDetailsService);
auth.authenticationProvider(authenticationProvider());
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(pwdEncoder);
return authenticationProvider;
}
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.authorizeRequests()
.antMatchers("/resources/**")
.permitAll()
.antMatchers("/rest/protected/**")
.access("hasAnyRole('ADMIN','USER','SUPER_ADMIN')")
.and()
.authorizeRequests()
.antMatchers("/rest/public/**")
.permitAll()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.usernameParameter("username")
.passwordParameter("password")
.defaultSuccessUrl("http://localhost:8100/", true)
.failureUrl("/login?error")
.loginProcessingUrl("/login")
.and()
.logout()
.permitAll()
.logoutSuccessUrl("/login?logout")
.and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.cors().configurationSource(corsConfigurationSource())
.and()
.exceptionHandling()
.accessDeniedPage("/pages/accessDenied");
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200","http://localhost:8080"));
configuration.setAllowedMethods(Arrays.asList("GET","POST", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("x-requested-with"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
這將使您僅使用 maven 即可開發和編譯所有內容
安傑洛
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.