mike-neckのブログ

JavaかJavaFXかJavaEE(なんかJava8が多め)

同一のURLに同じHTTPメソッドで異なるパラメーターを送った時に異なるメソッドを割り当てる

同じURL(/foo/bar)に異なるメソッド(baz(Baz baz)qux(Qux qux) の二つのメソッド)を割り当てる方法

@Canonical
class Text {
    String text
}

@Canonical
class Bidirecional {
    String question
    String answer1
    String answer2
}

@Canonical
class Result<T> {
    T content
    int id
}

@RestController
@RequestMapping(path = '/app')
class AppController {

    def map = [:]

    def index = new AtomicInteger(1)

    @PostMapping(consumes = 'application/json', produces = 'application/json', headers = 'Type=text')
    ResponseEntity<Result<Text>> postText(@RequestBody Text text) {
        def i = index.getAndIncrement()
        map[i] = text
        println text
        ResponseEntity.ok(new Result(id: i, content: text))
    }

    @PostMapping(consumes = 'application/json', produces = 'application/json', headers = 'Type=bidirectional')
    ResponseEntity<Result<Bidirecional>> postBidirectional(@RequestBody Bidirecional item) {
        def i = index.getAndIncrement()
        map[i] = item
        println item
        ResponseEntity.ok(new Result(id: i, content: item))
    }
}

ヘッダーを変えると異なるメソッドでも同一のURLに割り当てられるらしい