DEV Community

Composite
Composite

Posted on • Edited on

How to run SPA webapp on Spring Boot 2.x

TL;DR scroll down, get the sources below and taste it.

Most common web server with SPA flavor, All routes will forward to /index.html.
Yes. Spring boot also can do this. but it's pretty hard to figure it out until now. let's do this.

How much difficult to resolve this?
touch application.properties? NO.
write @Configuration? NOPE.
write @ControllerAdvice? NAH.
Why don't think easy peasy lemon squeezy?

just write a class with @Controller and implements ErrorController interface.
that's all. here's the code!

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class SpaErrorController implements ErrorController {

    @RequestMapping("/error")
    public Object error(HttpServletRequest request, HttpServletResponse response) {
        // place your additional code here (such as error logging...)
        if (request.getMethod().equalsIgnoreCase(HttpMethod.GET.name())) {
            response.setStatus(HttpStatus.OK.value()); // optional.
            return "forward:/index.html"; // forward to static SPA html resource.
        } else {
            return ResponseEntity.notFound().build(); // or your REST 404 blabla...
        }
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}
Enter fullscreen mode Exit fullscreen mode

Don't think other things, just compile and run.
You'll never see whitelabel error page and ALL routes will foward to index.html.
it's SPA style.

I'm using this solution in real world. ye... uhmm.. pretty good.

But remember, splitting front-end and back-end will be better choice; because of REUSABLE, comfortable deploying, other good point that you know.

Top comments (1)

Collapse
 
bravemaster619 profile image
bravemaster619

LOL, never thought this way. What a hack!