springboot/springMVC中controller层设计(编解码)

0.SpringMVC中参数解析原理

1.入参出参类型限定

(此处以入参出参为json类型为例)
图片.png

此外,还支持,xml,text等多种类型:
springboot/springMVC中controller层设计(编解码)_第1张图片
图片.png

2.入参是json类型,但是参数个数不确定

2.1方法一:

    @PostMapping("/master")
    public List master(@RequestBody Map map){
        System.out.println(map);
        return stuService.hello();
    }

postman访问,入参示例:
springboot/springMVC中controller层设计(编解码)_第2张图片
图片.png

打印的结果示例:

{first_name=Douglas, last_name=Fir, age=35, about=I like to build cabinets, interests=forestry}

2.2方法二:

    @PostMapping("/master")
    public List master(@RequestBody String params){
        Map map = JSON.parseObject(params, Map.class);
        Set keys = map.keySet();
        for (String key : keys){
            System.out.println(key + "=============" + map.get(key));
        }
        return stuService.hello();
    }

postman与上述2.1调用相同时,打印结果示例:

about=============I like to build cabinets
last_name=============Fir
interests=============forestry
first_name=============Douglas
age=============35

3.springMVC实现路径的模糊匹配

?: 匹配一个字符
* : 匹配任意字符
**: 匹配多层路径

3.1下述可以匹配的规则如:

http://localhost:8081/hello/tom/20/a/b/c/d/e/f
    @RequestMapping(path = "/hello/{name}/{age}/**")
    @ResponseBody
    public Object hello(@PathVariable("name") String name, 
                        @PathVariable("age") Integer age, 
                        HttpServletRequest request){
        return request.getRequestURL();
    }

3.2下述可以匹配的url为:

http://localhost:8081/world/abc
    @RequestMapping(path = "/world/{zzz:.*}")
    @ResponseBody
    public Object world(HttpServletRequest request){
        return request.getRequestURL();
    }

3.3采用代理模式修改RestTemplate

@AllArgsConstructor
public abstract class FilterRestTemplate implements RestOperations {
    @Delegate  // lombok的注解
    protected volatile RestTemplate restTemplate;
}

4.常见问题

4.1编解码问题

服务端

springboot/springMVC中controller层设计(编解码)_第3张图片
controller层.png

前端




    
    hello
    



https://www.jianshu.com/p/53b5bd0f1d44 (两种POST格式)

参考资源
https://www.cnblogs.com/007tangtao/p/9251861.html?utm_source=debugrun&utm_medium=referral

你可能感兴趣的:(springboot/springMVC中controller层设计(编解码))