Spring Boot-Angular - Entering Url in Address Bar results in 404

后端 未结 3 1818
鱼传尺愫
鱼传尺愫 2020-12-17 04:15

Need help on the basics - I have integrated Angular and Spring Boot. I made production build of the Angular app and copied the 6 files in the Spring boot static resource fo

相关标签:
3条回答
  • 2020-12-17 04:48

    If you don't use Spring MVC (for example, you are using Jersey), you can also solve this by using a javax.servlet.Filter:

    @Component
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public class AngularRoutingFilter implements Filter {
    
      @Override
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = ((HttpServletRequest) request);
        String requestURI = httpServletRequest.getRequestURI();
    
        if (shouldDispatch(requestURI)) {
            request.getRequestDispatcher("/").forward(request, response);
        } else {
            chain.doFilter(request, response);
        }
      }
    
      @Override
      public void init(FilterConfig filterConfig) {}
    
      @Override
      public void destroy() {}
    
      private boolean shouldDispatch(String requestURI) {
        /* Exclude/Inlclude URLs here */
        return !(requestURI.startsWith("/api") || requestURI.equals("/"));
      }
    
    }
    
    0 讨论(0)
  • 2020-12-17 04:49

    In the class where you have extended WebMvcConfigurerAdapter in Spring Boot, inside addViewControllers method, you should do something like this

    @Override
        public void addViewControllers(final ViewControllerRegistry registry) {
            super.addViewControllers(registry);
          registry.addViewController("/myTask").setViewName("forward:/");
     }
    

    for forwarding, all request, you can do registry.addViewController("/**").setViewName("forward:/");

    Update Thanks Jonas for the Suggestion. Since WebMvcConfigurerAdapter is deprecated in Spring 5.0, you can implement the above logic by extending WebMvcConfigurer

    0 讨论(0)
  • 2020-12-17 04:56
    // the perfect solution(from jhipster)
    @Controller
    public class ClientForwardController {
        @GetMapping(value = "/**/{path:[^\\.]*}")
        public String forward() {
            return "forward:/";
        }
    }
    
    0 讨论(0)
提交回复
热议问题