SpringMVC SpringBoot Get request receives complex parameters

cutting edge

For complex interface requests, POST JSON data is generally used, and the backend uses @RequestBody to receive it.
However, for some people who are obsessed with cleanliness or those who want to strictly follow the Restful style, the query data is to use GET, how? Realize it?

Request

@Data
public class MyRequest{
    
    
    private String key;
    
    private String[] keys;

    private Map<String, String[]> keyValues;
}

Controller

@RestController
@RequestMapping("my-controller")
public class MyController

	@GetMapping("request1")
    public String request1(MyRequest request) {
    
    
    	return JSON.toString(request);
    }
}

run

get http://localhost/my-controller/request1?key=k1&keys=k2,k3&keyValues[k4]=v41,v42&keyValues[k5]=v51,v52

result

{
    
    
	"key": "k1",
	"keys": ["k2", "k3"]
	"keyValues": {
    
    
		"k4": ["v41", "v42"],
		"k5": ["v51", "v52"]
	}
}

GET / JSON POST dual support

The above method currently has a problem, although the final Map instance of the keyValues ​​field is LinkedHashMap, which can theoretically maintain the same order as the request, but Spring will first sort all the parameters when parsing the URL request parameters (the specific code is not found ), so keyValues ​​actually achieves the effect of TreeMap, that is, the keys are sorted from small to large. If you need to keep the order of the request, you can only use the POST JSON method.
In addition, both GET and JOSN POST support:

@RestController
@RequestMapping("my-controller")
public class MyController

	@RequestMapping("request1")
    public String request1(MyRequest requestGet,
        @RequestBody(required = false) MyRequest request) {
    
    
        
        if (request = null) {
    
    
        	request = requestGet;
		}
		
    	return JSON.toString(request);
    }
}

PS: No one should use such a weird usage

Guess you like

Origin blog.csdn.net/qq_39609993/article/details/124450565