简体   繁体   中英

Spring Boot REST controller only matches with trailing “/”

I have a controller such as:

@RestController
@RequestMapping("/foo")
public class ServicesController {

    @RequestMapping(value="/", method=RequestMethod.GET)
    public Something doStuff() {
        ...
    }
}

For my domain www.bar.com , the request mapping will be called when I visit www.bar.com/foo/ , but not when I visit www.bar.com/foo . How can I make Spring trigger the same method for both www.bar.com/foo/ and www.bar.com/foo ?

Well, if you take a look at your own code, you're saying that to access your ServicesController , you must go to /foo , and that to access your doStuff , you must go to / .

In short, you're saying that to call your doStuff method in your ServicesController , you must go to /foo/ .

The right way in my opinion, to have a 'default' method for a class, you can do something like:

@RestController
@RequestMapping("/foo")
public class ServicesController {

    @RequestMapping(method=RequestMethod.GET)
    public Something doStuff() {
    }
}

You may add another value like,

@RequestMapping(value={"","/"}, method=RequestMethod.GET)
public Something doStuff() {
    ...
}

this will trigger for both the www.bar.com/foo/ and www.bar.com/foo

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