简体   繁体   中英

How to specify all routes except one?

I'm trying to overwrite my old project from native JS to React with MobX. My application has several pages and I want to use react-router to handle them. For that I need to return index.html page for all routes from my Spring-boot controller:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class RoutesController {
    @RequestMapping(value = { "", "/**" }, method = RequestMethod.GET)
    public String index() {
        return "index";
    }
}

Also I have special folder for static components on embedded Apache Tomcat server. This folder contains build.js for my client-side application. Controller presented above can serve all requests to server with index.html page, but I have also client-side application on /static/** route. How can I specify all routes in my controller except /static/** ?

I solved my problem. To get only one page for all requests your controller must implement ErrorController and two methods: error and getErrorPath . Here is an example:

import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class RoutesController implements ErrorController {
    private static final String PATH = "/error";

    @RequestMapping(value = PATH)
    public String error() {
        return "index";
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }
}

Server get the request and will not find any routes, so it will return result of error method.

Maybe that's not the best solution, but after three days of searching the Internet I have not found anything better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM