如何将角度与弹簧靴相结合,以查看弹簧靴口上的角度网状界面?

问题描述 投票:0回答:2

我有后端弹簧启动应用程序和使用angular4开发的前端。由于这两个端口在部署时在不同的端口(8080,4200)上运行,因此它不显示任何UI。在本地,使用下面的起始角度服务器在localhost:4200上完全正常工作并显示web界面:

ng serve --proxy-config proxy.conf.json

其中proxy.conf.json有内容:

{
  "*": {
    "target": "http://localhost:8080",
    "secure": false,
    "logLevel": "debug"
  }
}

但是在尝试与spring boot app(localhost:8080)集成时却没有。可能需要在部署之前烘焙ng业务逻辑(node / npm install等)。

所以我使用ng build将生成的文件复制到输出目录--src / main / resources / static,现在它在spring-boot app路径中。启动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无法理解角度内容以及如何路由到主要组件。

以下是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来提供服务?

任何帮助,非常感谢!

java angular spring-boot angular-cli angular4-router
2个回答
1
投票

你可以使用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.propertiesI有我的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是一个经典的弹簧后端。您必须告诉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可以解决这个问题配置,在后端方面,弹簧安全就是这样的:

@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开发和编译所有

安杰洛


0
投票

请使用存档实用程序打开jar文件,并查看其中是否有可用的静态文件。如果它们可用,您需要告诉Spring您输入地址栏的URL实际上是Angular路由:

@Controller
public class Routing {

    @RequestMapping({ "", "/login", "/products/**" })
    public String gui() {
        return "forward:/index.html";
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.