Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure Spring Boot for SPA frontend

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);
    } 
like image 533
Rudziankoŭ Avatar asked Nov 23 '16 16:11

Rudziankoŭ


2 Answers

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.

like image 76
EpicPandaForce Avatar answered Nov 12 '22 16:11

EpicPandaForce


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").

like image 36
Chris Gaskill Avatar answered Nov 12 '22 18:11

Chris Gaskill