Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

angularjs - Redirect unknown requests to index.html in springboot

I'm trying to get an Angular2 app served up through a springboot web application. I've found lots of examples of how to do this very simply:

https://spring.io/blog/2015/01/12/spring-and-angular-js-a-secure-single-page-application#using-spring-boot-cli

https://github.com/zouabimourad/angular2-spring/tree/master/front

https://github.com/ehirsch/spring-angular2

However, these examples are very simple, and they just basically show how to display static content that happens to be Angular.

None of them show how to handle any of the URLs (I think they're called routes) the Angular2 app uses that don't map to "real" resources.

Eg. We have a "/login" route in the Angular app, but we don't have a @Controller/@RequestMapping("/login") for this, I want Spring to render index.html when it see's a request for "/login".

Generically - I want Spring to render "index.html" whenever it can't an actual resource. Is there a way to set a default view for all requests that can't be mapped to something or found?

I've tackled this before by using an htaccess file and have apache handle this:

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteRule . index.html [L]
   ErrorDocument 404 /index.html
</IfModule>

But I can't use apache or nginx in this case.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As a work-a-round I've added the Angular Routes in a RequestMapping annotation and pointed them all at the index.html:

@RequestMapping({"/login", "/logout"})
public String index() { return "index.html"; }

Edit: As a better work-a-round, you can make the controller implement ErrorController, override the getErrorPath method, then add a mapping for /error which will act as a catch-all (or mapping missing) method.

@Controller
public class TheOneController implements ErrorController {

    @RequestMapping("/error")
    public String index() {
        return "index.html";
    }

    @Override
    public String getErrorPath() {
        return "index.html";
    }
}

Now the index method will handle anything that can't be found and render the index.html.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...