在Tomcat上部署一个Spring Boot和Angular应用的WAR文件

8
我创建了一个 Angular 和 Spring Boot 应用程序,并想将其部署在 Tomcat 服务器上。为此,我将一个 Angular 项目复制到一个 Spring Boot 项目中,并提供了一个 pom.xml 来创建 WAR 文件。之后我将 WAR 文件部署到 Tomcat 上并启动了它。那是什么?
答:这是一个将 Angular 和 Spring Boot 集成在一起的 Web 应用程序,通过将 Angular UI 放置在 Spring Boot 应用程序中来实现集成。
  1. Angular 的 index.html 中的 base href
  2. 我需要提供哪个上下文路径?
  3. 我需要在 application.properties 中提供 server.port 吗?
答:
  1. base href 在 Angular 的 index.html 中。
  2. 应该提供 Spring Boot 应用程序的上下文路径。
  3. 不需要提供 server.port ,Tomcat 将使用默认端口。
我遇到了 404 错误:

Enter image description here

Enter image description here

控制台错误信息
org.springframework.security.web.session.SessionManagementFilter@af8f6da, org.springframework.security.web.access.ExceptionTranslationFilter@7551f180, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@67dc6d01]
     2020-10-14 19:17:57.066  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerAdapter   : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@3472387b: startup date [Wed Oct 14 19:17:26 IST 2020]; root of context hierarchy
     2020-10-14 19:17:57.071  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerAdapter   : Detected @ModelAttribute methods in globalController
     2020-10-14 19:17:57.100  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/ || ],methods=[OPTIONS],produces=[application/hal+json || application/json]}" onto public org.springframework.http.HttpEntity<?> org.springframework.data.rest.webmvc.RepositoryController.optionsForRepositories()
     2020-10-14 19:17:57.101  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/ || ],methods=[HEAD],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<?> org.springframework.data.rest.webmvc.RepositoryController.headForRepositories()
     2020-10-14 19:17:57.102  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/ || ],methods=[GET],produces=[application/hal+json || application/json]}" onto public org.springframework.http.HttpEntity<org.springframework.data.rest.webmvc.RepositoryLinksResource> org.springframework.data.rest.webmvc.RepositoryController.listRepositories()
     2020-10-14 19:17:57.104  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}],methods=[GET],produces=[application/hal+json || application/json]}" onto public org.springframework.hateoas.Resources<?> org.springframework.data.rest.webmvc.RepositoryEntityController.getCollectionResource(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.support.DefaultedPageable,org.springframework.data.domain.Sort,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler) throws org.springframework.data.rest.webmvc.ResourceNotFoundException,org.springframework.web.HttpRequestMethodNotSupportedException
     2020-10-14 19:17:57.105  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}],methods=[HEAD],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<?> org.springframework.data.rest.webmvc.RepositoryEntityController.headCollectionResource(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.support.DefaultedPageable) throws org.springframework.web.HttpRequestMethodNotSupportedException
     2020-10-14 19:17:57.106  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}/{id}],methods=[DELETE],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<?> org.springframework.data.rest.webmvc.RepositoryEntityController.deleteItemResource(org.springframework.data.rest.webmvc.RootResourceInformation,java.io.Serializable,org.springframework.data.rest.webmvc.support.ETag) throws org.springframework.data.rest.webmvc.ResourceNotFoundException,org.springframework.web.HttpRequestMethodNotSupportedException
     2020-10-14 19:17:57.107  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}/{id}],methods=[PATCH],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryEntityController.patchItemResource(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.PersistentEntityResource,java.io.Serializable,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler,org.springframework.data.rest.webmvc.support.ETag,java.lang.String) throws org.springframework.web.HttpRequestMethodNotSupportedException,org.springframework.data.rest.webmvc.ResourceNotFoundException
     2020-10-14 19:17:57.108  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}/{id}],methods=[OPTIONS],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<?> org.springframework.data.rest.webmvc.RepositoryEntityController.optionsForItemResource(org.springframework.data.rest.webmvc.RootResourceInformation)
     2020-10-14 19:17:57.109  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}],methods=[OPTIONS],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<?> org.springframework.data.rest.webmvc.RepositoryEntityController.optionsForCollectionResource(org.springframework.data.rest.webmvc.RootResourceInformation)
     2020-10-14 19:17:57.120  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}],methods=[POST],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryEntityController.postCollectionResource(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.PersistentEntityResource,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler,java.lang.String) throws org.springframework.web.HttpRequestMethodNotSupportedException
     2020-10-14 19:17:57.124  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}/{id}],methods=[HEAD],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<?> org.springframework.data.rest.webmvc.RepositoryEntityController.headForItemResource(org.springframework.data.rest.webmvc.RootResourceInformation,java.io.Serializable,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler) throws org.springframework.web.HttpRequestMethodNotSupportedException
     2020-10-14 19:17:57.125  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}],methods=[GET],produces=[application/x-spring-data-compact+json || text/uri-list]}" onto public org.springframework.hateoas.Resources<?> org.springframework.data.rest.webmvc.RepositoryEntityController.getCollectionResourceCompact(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.support.DefaultedPageable,org.springframework.data.domain.Sort,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler) throws org.springframework.data.rest.webmvc.ResourceNotFoundException,org.springframework.web.HttpRequestMethodNotSupportedException
     2020-10-14 19:17:57.127  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}/{id}],methods=[PUT],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<? extends org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryEntityController.putItemResource(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.PersistentEntityResource,java.io.Serializable,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler,org.springframework.data.rest.webmvc.support.ETag,java.lang.String) throws org.springframework.web.HttpRequestMethodNotSupportedException
     2020-10-14 19:17:57.130  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}/{id}],methods=[GET],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<org.springframework.hateoas.Resource<?>> org.springframework.data.rest.webmvc.RepositoryEntityController.getItemResource(org.springframework.data.rest.webmvc.RootResourceInformation,java.io.Serializable,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler,org.springframework.http.HttpHeaders) throws org.springframework.web.HttpRequestMethodNotSupportedException
     2020-10-14 19:17:57.137  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}/{id}/{property}],methods=[GET],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.followPropertyReference(org.springframework.data.rest.webmvc.RootResourceInformation,java.io.Serializable,java.lang.String,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler) throws java.lang.Exception
     2020-10-14 19:17:57.138  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}/{id}/{property}/{propertyId}],methods=[GET],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.followPropertyReference(org.springframework.data.rest.webmvc.RootResourceInformation,java.io.Serializable,java.lang.String,java.lang.String,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler) throws java.lang.Exception
     2020-10-14 19:17:57.139  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}/{id}/{property}],methods=[GET],produces=[application/x-spring-data-compact+json || text/uri-list]}" onto public org.springframework.http.ResponseEntity<org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.followPropertyReferenceCompact(org.springframework.data.rest.webmvc.RootResourceInformation,java.io.Serializable,java.lang.String,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler) throws java.lang.Exception
     2020-10-14 19:17:57.140  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}/{id}/{property}],methods=[PATCH || PUT || POST],consumes=[application/json || application/x-spring-data-compact+json || text/uri-list],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<? extends org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.createPropertyReference(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.http.HttpMethod,org.springframework.hateoas.Resources<java.lang.Object>,java.io.Serializable,java.lang.String) throws java.lang.Exception
     2020-10-14 19:17:57.141  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}/{id}/{property}/{propertyId}],methods=[DELETE],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.deletePropertyReferenceId(org.springframework.data.rest.webmvc.RootResourceInformation,java.io.Serializable,java.lang.String,java.lang.String) throws java.lang.Exception
     2020-10-14 19:17:57.142  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}/{id}/{property}],methods=[DELETE],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<? extends org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryPropertyReferenceController.deletePropertyReference(org.springframework.data.rest.webmvc.RootResourceInformation,java.io.Serializable,java.lang.String) throws java.lang.Exception
     2020-10-14 19:17:57.144  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}/search],methods=[OPTIONS],produces=[application/hal+json || application/json]}" onto public org.springframework.http.HttpEntity<?> org.springframework.data.rest.webmvc.RepositorySearchController.optionsForSearches(org.springframework.data.rest.webmvc.RootResourceInformation)
     2020-10-14 19:17:57.148  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}/search/{search}],methods=[GET],produces=[application/x-spring-data-compact+json]}" onto public org.springframework.hateoas.ResourceSupport org.springframework.data.rest.webmvc.RepositorySearchController.executeSearchCompact(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.http.HttpHeaders,org.springframework.util.MultiValueMap<java.lang.String, java.lang.Object>,java.lang.String,java.lang.String,org.springframework.data.rest.webmvc.support.DefaultedPageable,org.springframework.data.domain.Sort,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler)
     2020-10-14 19:17:57.149  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}/search],methods=[HEAD],produces=[application/hal+json || application/json]}" onto public org.springframework.http.HttpEntity<?> org.springframework.data.rest.webmvc.RepositorySearchController.headForSearches(org.springframework.data.rest.webmvc.RootResourceInformation)
     2020-10-14 19:17:57.151  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}/search/{search}],methods=[GET],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<?> org.springframework.data.rest.webmvc.RepositorySearchController.executeSearch(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.util.MultiValueMap<java.lang.String, java.lang.Object>,java.lang.String,org.springframework.data.rest.webmvc.support.DefaultedPageable,org.springframework.data.domain.Sort,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler,org.springframework.http.HttpHeaders)
     2020-10-14 19:17:57.152  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}/search/{search}],methods=[OPTIONS],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<java.lang.Object> org.springframework.data.rest.webmvc.RepositorySearchController.optionsForSearch(org.springframework.data.rest.webmvc.RootResourceInformation,java.lang.String)
     2020-10-14 19:17:57.152  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}/search],methods=[GET],produces=[application/hal+json || application/json]}" onto public org.springframework.data.rest.webmvc.RepositorySearchesResource org.springframework.data.rest.webmvc.RepositorySearchController.listSearches(org.springframework.data.rest.webmvc.RootResourceInformation)
     2020-10-14 19:17:57.153  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped "{[/{repository}/search/{search}],methods=[HEAD],produces=[application/hal+json || application/json]}" onto public org.springframework.http.ResponseEntity<java.lang.Object> org.springframework.data.rest.webmvc.RepositorySearchController.headForSearch(org.springframework.data.rest.webmvc.RootResourceInformation,java.lang.String)
     2020-10-14 19:17:57.161  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.BasePathAwareHandlerMapping    : Mapped "{[/profile],methods=[GET]}" onto org.springframework.http.HttpEntity<org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.ProfileController.listAllFormsOfMetadata()
     2020-10-14 19:17:57.162  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.BasePathAwareHandlerMapping    : Mapped "{[/profile],methods=[OPTIONS]}" onto public org.springframework.http.HttpEntity<?> org.springframework.data.rest.webmvc.ProfileController.profileOptions()
     2020-10-14 19:17:57.163  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.BasePathAwareHandlerMapping    : Mapped "{[/profile/{repository}],methods=[OPTIONS],produces=[application/alps+json]}" onto org.springframework.http.HttpEntity<?> org.springframework.data.rest.webmvc.alps.AlpsController.alpsOptions()
     2020-10-14 19:17:57.164  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.BasePathAwareHandlerMapping    : Mapped "{[/profile/{repository}],methods=[GET],produces=[application/alps+json || */*]}" onto org.springframework.http.HttpEntity<org.springframework.data.rest.webmvc.RootResourceInformation> org.springframework.data.rest.webmvc.alps.AlpsController.descriptor(org.springframework.data.rest.webmvc.RootResourceInformation)
     2020-10-14 19:17:57.165  INFO 5176 --- [ost-startStop-1] o.s.d.r.w.BasePathAwareHandlerMapping    : Mapped "{[/profile/{repository}],methods=[GET],produces=[application/schema+json]}" onto public org.springframework.http.HttpEntity<org.springframework.data.rest.webmvc.json.JsonSchema> org.springframework.data.rest.webmvc.RepositorySchemaController.schema(org.springframework.data.rest.webmvc.RootResourceInformation)
     2020-10-14 19:17:57.424  INFO 5176 --- [ost-startStop-1] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path '/actuator'
     2020-10-14 19:17:57.503  INFO 5176 --- [ost-startStop-1] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/health],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
     2020-10-14 19:17:57.505  INFO 5176 --- [ost-startStop-1] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator/info],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
     2020-10-14 19:17:57.508  INFO 5176 --- [ost-startStop-1] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "{[/actuator],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto protected java.util.Map<java.lang.String, java.util.Map<java.lang.String, org.springframework.boot.actuate.endpoint.web.Link>> org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping.links(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
     2020-10-14 19:17:58.181  INFO 5176 --- [ost-startStop-1] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
     2020-10-14 19:17:58.376  INFO 5176 --- [ost-startStop-1] com.springboot.wabit.WabitApplication    : Started WabitApplication in 33.544 seconds (JVM running for 58.21)
     2020-10-14 19:17:58.556  INFO 5176 --- [           main] org.apache.catalina.startup.Catalina     : Server startup in 56058 ms
     2020-10-14 19:18:00.111  INFO 5176 --- [nio-8086-exec-2] o.a.c.c.C.[.[localhost].[/wabSpring]     : Initializing Spring FrameworkServlet 'dispatcherServlet'
     2020-10-14 19:18:00.111  INFO 5176 --- [nio-8086-exec-2] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
     2020-10-14 19:18:00.214  INFO 5176 --- [nio-8086-exec-2] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 103 ms
     request ===null

项目结构

在这里输入图片描述

文件 pom.xml

<build>
    <finalName>wabITSpring</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>${maven-war-plugin.version}</version>
                    <executions>
                        <execution>
                            <goals>
                                <goal>war</goal>
                            </goals>
                            <phase>package</phase>
                        </execution>
                    </executions>
                    <configuration>
                        <warSourceIncludes>WEB-INF/**,META-INF/**</warSourceIncludes>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                        <warSourceDirectory>target/classes/static/</warSourceDirectory>
                        <webResources>
                            <resource>
                                <directory>src/main/webapp</directory>
                                <includes>
                                    <include>WEB-INF/**</include>
                                </includes>
                            </resource>
                        </webResources>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

    <profiles>
        <profile>
            <id>war</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-war-plugin</artifactId>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

文件 index.html

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Spring Boot + Angular 8</title>
<base href="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,
500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Prompt:wght@300&display=swap" rel="stylesheet">
<script type="text/javascript">

    var cfgApiBaseUrl = "https://localhost:8080/wabITSpring/onlineshopping"

</script>
<link rel="stylesheet" href="styles.ca7355ed03bb6e9eec0a.css">
</head>
<body>

application.properties

server.port=8080
server.servlet.context-path=/wabITSpring/onlineshopping

SecurityConfig.java

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
DataSource dataSource;
@Autowired
private CustomUserDetailService customUserDetailService;

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/resources/**");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable().authorizeRequests().
        antMatchers("/**").permitAll().antMatchers("/")
        .hasRole("anonymousUser").anyRequest().authenticated()
        .and().sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
        .exceptionHandling()
                    .accessDeniedPage("/access-denied").and()
                    .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                    .addFilter(new JWTAuthorizationFilter(authenticationManager(),
         customUserDetailService));
    }
}

JWTAuthorizationFilter.java

public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
    private final CustomUserDetailService customUserDetailService;

    public JWTAuthorizationFilter(AuthenticationManager authenticationManager, CustomUserDetailService customUserDetailService) {
        super(authenticationManager);
        this.customUserDetailService = customUserDetailService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {

        String header = request.getHeader(HEADER_STRING);

        System.out.println("request ===" + request.getHeader("Authorization"));

        if (header == null || !header.startsWith(TOKEN_PREFIX)) {
            chain.doFilter(request, response);
            return;
        }
        UsernamePasswordAuthenticationToken authenticationToken = getAuthenticationToken(request);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        chain.doFilter(request, response);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    }

    private UsernamePasswordAuthenticationToken getAuthenticationToken(HttpServletRequest request) {
        String token = request.getHeader(HEADER_STRING);
        if (token == null)
            return null;
        String username = Jwts.parser().setSigningKey(SECRET)
                .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                .getBody()
                .getSubject();
        UserDetails userDetails = customUserDetailService.loadUserByUsername(username);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                  return username != null ?
                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()) : null;
    }
}

应用程序本身运行良好,但每当我尝试将其部署为WAR文件到Tomcat上时,虽然前端可以看到,但无法连接到后端。

@Paweł Głowacz,是的,我尝试将端口更改为8080、8086,甚至不指定任何端口,但都无法工作。我没有证书。 - vidy
除了使用WAR文件之外,是否有其他部署Angular + Spring Boot的方法? - vidy
你能访问Tomcat的管理控制台吗?我想应该有可能看到应用程序部署的路径。甚至在浏览器中打开应用程序路径也是可能的。然后你就可以验证Angular应用程序是否尝试更正路径。 - mico
@mico 是的,我可以看到Tomcat的管理控制台,并且应用部署在/wabSpring上,上下文路径是/onlineshopping。如果我尝试访问localhost:8080/wabSpring/onlineshopping/plan/info,它会显示一个白色页面。 - vidy
一个建议:https://stackoverflow.com/a/63092844/1679484 - Amit Parashar
显示剩余2条评论
3个回答

11

步骤1:为Angular创建构建

从共享的项目结构可以看出,您在同一位置拥有后端和前端代码。理想的方式是为Angular创建构建/工件,它将在Angular目录内创建目标文件夹,其中包含UI资源。 要创建相同的内容,您可以根据您的环境和配置使用以下命令。

ng build --configuration=<env>
ng build --prod

步骤2:将UI与Spring Boot集成

然后,您可以在src/main/resources中创建一个名为static的文件夹,并将UI资源(目标文件夹内的文件)粘贴到此静态文件夹中。

步骤3:部署配置

步骤1:在文件pom.xml中更改打包选项为war

<packaging>war</packaging>

步骤2:继承SpringBootServletInitializer

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

/**
 * This is a helper Java class that provides an alternative to creating a {@code web.xml}.
 * This will be invoked only when the application is deployed to a Servlet container like Tomcat, JBoss etc.
 */
public class ApplicationWebXml extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(ApplicationApp.class);
    }
}

步骤 3:创建WAR文件。

mvn clean install

好的,我们完成了!我们可以访问以下端点:

http://localhost:8080/context-path/endpoint OR
http://localhost:8080/war-filename/endpoint

我们也可以按照以下方式创建war的概要文件:

<properties>
    <maven-war-plugin.version>3.2.3</maven-war-plugin.version>
</properties>

     <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>${maven-war-plugin.version}</version>
                    <executions>
                        <execution>
                            <goals>
                                <goal>war</goal>
                            </goals>
                            <phase>package</phase>
                        </execution>
                    </executions>
                    <configuration>
                        <warSourceIncludes>WEB-INF/**,META-INF/**</warSourceIncludes>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                        <warSourceDirectory>target/classes/static/</warSourceDirectory>
                        <webResources>
                            <resource>
                                <directory>src/main/webapp</directory>
                                <includes>
                                    <include>WEB-INF/**</include>
                                </includes>
                            </resource>
                        </webResources>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>


    <profiles>
        <profile>
            <id>war</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-war-plugin</artifactId>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

部署WAR文件到Tomcat(Spring Boot + Angular)


1
谢谢。现在可以看到前端页面了。我几乎尝试了所有在互联网上找到的解决方案,但是这是我第一次看到我的前端页面。但是我仍然遇到连接后端的问题,我需要一些帮助。 - vidy
这个是URL地址:http://localhost:8080/wabITSpring/#/,WAR文件名为wabITSpring。我需要在contextpath中放置#吗?我已经在问题中分享了项目的更新链接。 - vidy
如果我使用Eclipse在Tomcat服务器上运行该项目,则会遇到相同的错误。在调试时,JWTAuthorizationFilter.java类中显示请求== null。 - vidy
你能否更新问题并分享日志,以及从网络选项卡中获取API调用的状态码? - Romil Patel
你好,@vidy。你可能会收到401或403状态码,而不是404。从上面分享的代码来看,似乎你的angular代码没有使用令牌设置“Authorization”头部信息。 - Romil Patel
显示剩余5条评论

3
可以将所有内容打包成一个WAR文件,但我认为将不同的应用程序(后端WAR文件和前端目标内容)混合在一起并不方便,因为我们已经在寻找哪个部分响应以及它们的位置。
实际上,更容易的方法是应用以下配置:
<Host appBase="webapps"
      autoDeploy="false" name="localhost" unpackWARs="true"
      xmlNamespaceAware="false" xmlValidation="false">

      <!--   ...    -->

    <Context docBase="/home/stuff" path="/static" />
</Host>

Content标签告诉前端页面位于哪里。Angular作为前端看起来很棒,但实际上只是Tomcat服务器的静态页面。后端使用Java开发,需要一个服务器并从WAR文件中提供服务。

通过给定的docBase,将目标内容手动复制到/home/stuff文件夹,并在http://localhost:8080/static/路径下显示。您不需要在斜杠后面添加index.html文件,但如果出于某种原因确实需要,请添加它。这些文件位置和路径的值可以自由配置。此外,值得一提的是,配置文件的其他部分仅说明了配置文件中的位置。

所使用的配置文件是Tomcat的server.xml文件。

已部署的后端应用程序的路径可以在Tomcat的管理控制台中查看。

来源:

[1] 使用Apache Tomcat从WAR文件之外提供静态内容(包括网页)


2
你所做的所有步骤都是正确的,正如 Patel Romil所说。你唯一犯的错误就是在前端调用API。不要在URL中添加任何上下文路径,就像你在application.properties中添加的那样。
如果你的WAR文件部署在路径上,那么你在index.html中的URL将会是这样的。
var cfgApiBaseUrl = "https://localhost:8080/wabITSpring/"

你的应用程序不关心上下文路径,也不会有任何引用它的内容。如果你的控制器定义了一个路径为 /products,那么 Tomcat 将在 /wabITSpring/products 下提供此服务。
 var cfgApiBaseUrl = "https://localhost:8080/wabITSpring/products"

做到这一点,你的应用程序将成功运行。

1
谢谢,我按照你说的做了,最终我的项目前端和后端都启动了。我之前输入了上下文路径,这就是我一直收到404错误的原因。我被卡在这个问题上超过3周了。谢谢 :) - vidy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接