DEV Community

Composite
Composite

Posted on • Edited on

8 2

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.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (1)

Collapse
 
bravemaster619 profile image
bravemaster619

LOL, never thought this way. What a hack!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay