end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

spring boot for javaにおける pathパラメータやrequestパラメータの受取り

@PathVariable と、@RequestParam が、やってくれます。

サンプルコードは以下のとおりですが、json なStringでマルっと受信しても良い気がします

参考url Spring Boot 使い方メモ - Qiita

package jp.end0tknr.streamdoc.ctrl;

import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Sandbox {

    private static final Logger logger =
            LoggerFactory.getLogger(Sandbox.class);

    @RequestMapping(value="/SandboxRest/{userId}")
    public Map<String, Object> findDocs (
            @PathVariable String userId,
            @RequestParam String id,
            @RequestParam Map<String, Object> queryParameters,
            @RequestParam MultiValueMap<String, String> multiMap,
            Model model) {
        
        logger.info(queryParameters.toString());
        logger.info(multiMap.toString());
        // System.out.println("id=" + id);
        return queryParameters;
    }    
}

↑こう書いて、↓こうアクセスすると...

http://localhost:8080/SandboxRest/user123?id=100&name=hoge&name=fuga

↓このようにログに出力されます。

INFO 8416 [nio-8080-exec-1] ctrl.Sandbox : {id=100, name=hoge}
INFO 8416 [nio-8080-exec-1] ctrl.Sandbox : {id=[100], name=[hoge, fuga]}