Spring 5 MVC Angular 5 App抛出404错误

时间:2018-10-13 17:03:38

标签: angular spring-mvc

我知道之前曾有人问过这个问题,我已经尝试了几种解决方案,但无法正常工作。我正在使用Spring 5 MVC和/ src / main / webapp /中存在的angular应用。

访问基本路径时,该应用程序可以运行。问题出在我需要跳入应用内的路线时。当页面尝试使用URL中的路由加载时,它会引发404错误,因为Spring找不到为此的资源处理程序,但实际上我要它要做的只是转到应用程序的index.html可以处理。我试图将应用程序移动到/ src / main / webapp /中的“ app”文件夹中,您可以在下面看到资源处理程序和视图控制器。我为此应用程序还使用了摇摇欲坠,这会使事情变得复杂。任何帮助将不胜感激!

public class MvcConfiguration implements WebMvcConfigurer {...

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
    registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");   
    registry.addResourceHandler("/app/**").addResourceLocations("/app/");
}

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addRedirectViewController("/", "swagger-ui.html");
    registry.addViewController("/swagger").setViewName("redirect:/rest/swagger-ui.html");
    registry.addViewController("/app").setViewName("forward:/app/index.html");
}

以及下面的网络初始化类:

public class WebInitializer implements WebApplicationInitializer {

AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext();

@Override
public void onStartup(ServletContext container) {
    // Create the 'root' Spring application context
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(ApplicationConfiguration.class);

    // Manage the lifecycle of the root application context
    container.addListener(new ContextLoaderListener(rootContext));

    registerDispatcherServlet(container, MvcConfiguration.class, "/views/*", "/rest/*", "/swagger/*");

    container.addFilter("springSecurityFilterChain", new DelegatingFilterProxy("springSecurityFilterChain")).addMappingForUrlPatterns(null, false, "/*");

    CharacterEncodingFilter charEncodingFilter = new CharacterEncodingFilter();
    charEncodingFilter.setEncoding("UTF-8");
    container.addFilter("encoding-filter", charEncodingFilter).addMappingForUrlPatterns(null, false, "/*");

    container.addFilter("cors-filter", new CorsFilter()).addMappingForUrlPatterns(null, false, "/*");
}

1 个答案:

答案 0 :(得分:0)

您需要检查基本href属性。

<base href="/src/main/webapp/">