Spring Boot with AngularJS html5Mode

后端 未结 9 2248
长发绾君心
长发绾君心 2020-11-27 04:35

I start my web application with spring boot. It use a simple main class to start an embedded tomcat server:

@Configuration
@EnableAutoConfiguration
@Componen         


        
相关标签:
9条回答
  • 2020-11-27 04:51

    Use this controller to forward the URI to index.html in order to preserve AngularJS routes. Source https://spring.io/blog/2015/05/13/modularizing-the-client-angular-js-and-spring-security-part-vii

    @Controller
    public class ForwardController {
    
        @RequestMapping(value = "/**/{[path:[^\\.]*}")
        public String redirect() {
            // Forward to home page so that route is preserved.
            return "forward:/";
        }
    } 
    

    In this solution ForwardController forwards only paths, which are not defined in any other Controller nor RestController. It means if you already have:

    @RestController
    public class OffersController {
    
        @RequestMapping(value = "api/offers")
        public Page<OfferDTO> getOffers(@RequestParam("page") int page) {
            return offerService.findPaginated(page, 10);
        }
    } 
    

    both controllers are going to work properly - @RequestMapping(value = "api/offers") is checked before @RequestMapping(value = "/**/{[path:[^\\.]*}")

    0 讨论(0)
  • 2020-11-27 04:55

    1- first you create new Controller then copy and paste simple below code

    @Controller
    public class viewController {
    
     @RequestMapping(value = "/**/{[path:[^\\.]*}")
     public String redirect() {
        // Forward to home page so that route is preserved.
        return "forward:/";
     }
    
    }
    

    3- remove 2 below item from angular app

    $locationProvider.hashPrefix('!');
    $urlRouterProvider.otherwise("/");
    

    2- in angular application you must add $locationProvider.html5Mode(true); to app route

    3- Don't forget to place the base tag before any http request in your index.html file

    <head>
    <base href="/"> /* Or whatever your base path is */
    
    //call every http request for style and other 
    ...
    </head>
    

    it's work fine for me

    0 讨论(0)
  • 2020-11-27 04:59

    I found a solution I can live with it.

    @Controller
    public class ViewController {
    
        @RequestMapping("/")
        public String index() {
            return "index";
        }
    
        @RequestMapping("/app/**")
        public String app() {
            return "index";
        }
    }
    

    The angularjs app has to be under the subdomain app. If you do not want that you could create a subdomain like app.subdomain.com that mapps to your subdomain app. With this construct you have no conflicts with webjars, statis content and so on.

    0 讨论(0)
提交回复
热议问题