Configure Spring Boot for SPA frontend
Asked Answered
H

3

9

I have application where whole frontend part is laying in resource. I would like to separate things apart. And have separate server for UI, provided by gulp, for example.

So that I assume that my server should return index.html for all requests that are rendered by client side.

Eg: I have 'user/:id' rout that is managing by angular routing and doesn't need server for anything. How can I configure so that server will not reload or redirect me to anywhere?

My security config is following(don't know if it responsible for such things):

public class Application extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**").authorizeRequests().antMatchers("/", "/login**", "/webjars/**", "/app/**", "/app.js")
                .permitAll().anyRequest().authenticated().and().exceptionHandling()
                .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/")).and().logout()
                .logoutSuccessUrl("/").permitAll().and().csrf()
                .csrfTokenRepository(csrfTokenRepository()).and()
                .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
                .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
    } 
Headfirst answered 23/11, 2016 at 16:8 Comment(1)
I understand that Spring Boot was not meant to be used as a web server for static files or a proxy, but man, I am trying to do something similar and any Java dev I've asked in our company gives up trying after a few hours... I have done something similar in NodeJS/Express (also which is also not designed to serve static files) in a couple of lines..Urbanus
C
26

For routing, according to this guide at Using "Natural" Routes (specifically here), you have to add a controller that does the following:

@Controller
public class RouteController {
    @RequestMapping(value = "/{path:[^\\.]*}")
    public String redirect() {
        return "forward:/";
    }
}

Then using Spring Boot, the index.html loads at /, and resources can be loaded; routes are handled by Angular.

Cortege answered 23/11, 2016 at 16:16 Comment(6)
This doesn't cover URLs with another forward slash though. E.G. localhost:8080/im-covered and localhost:8080/im/not/coveredSieber
@Cortege What exactly does {[path:[^\\.]*} mean? Where does it come from? I understand the regex, I don't understand how Spring Boot handles the "path" part.Discourage
@BobbyBrown unfortunately all I know is that I followed this guide and it worked.Cortege
@Cortege same... I was just trying to figure out what path was. I guess @RequestMapping takes an object in a JSON like format.Discourage
This is a special syntax for named path variables. path: means that the part of URL matched by this regex will be bound to the @PathVariable with the corresponding name.Gangster
I don't understand why "/{path:[^\\.]*}" is working because it should match the path /. I would have written "/{path:[^\\.]+}"Lastditch
L
6

EpicPandaForce has a great answer, and I wanted to expand on it. The following endpoint will allow matching on nested routes as well. If you wanted to have an admin section, you can configure it to return a different index.html.

@Controller
class PageController {

    @GetMapping("/**/{path:[^\\.]*}")
    fun forward(request: HttpServletRequest): String? {
        if(request.requestURI.startsWith("/admin")) {
            return "forward:/admin/index.html"
        }
        return "forward:/index.html"
    }
}

This RequestMapping (or @GetMapping) works by excluding any request that contains a period (i.e. "index.html").

Lobo answered 17/5, 2019 at 13:54 Comment(2)
Not working with spring boot 2.7.0 :(Xanthophyll
@Xanthophyll With spring.mvc.pathMatch.matching-strategy=ANT_PATH_MATCHER you can change the default matching strategy that is now (in 2.7) defaulting to PATH_PATTERN_PARSER (this is the change between 2.7 and older ones)Caco
U
-1

If you are using Angular with Spring Data Rest, I think that the most straightforward way to do it is using angular hash location strategy.

Just putting this in the providers array in your app module:

{ provide: LocationStrategy, useClass: HashLocationStrategy }

and, obviously, import it.

Unseasoned answered 22/7, 2017 at 6:29 Comment(1)
Don't settle for the HashLocationStrategy to get over this problem as it is not recommended by Angular: angular.io/guide/router#which-strategy-is-bestMaquette

© 2022 - 2024 — McMap. All rights reserved.