美文网首页js css html
Spring Boot Web 请求参数之注解

Spring Boot Web 请求参数之注解

作者: Tinyspot | 来源:发表于2022-11-27 23:01 被阅读0次

    1. @RequestParam

    • 修饰参数,将名字与参数进行绑定,相当于ServletRequest.getParameter()

    请求URL:http://localhost:8080/hello?name=111

    @RequestMapping("/hello")
    public String hello(String name) {
        return "hello: " + name;
    }
    

    若请求参数与接收参数名不一致
    请求URL:http://localhost:8080/hello?username=111

    @RequestMapping("/hello")
    public String hello(@RequestParam("username") String name) {
        return "hello: " + name;
    }
    

    1.1 参数封装为 Map<String, String>

    请求地址的参数默认封装在 Map<String, String>

    @RequestMapping("/show")
    public Map<String, Object> show(@RequestParam("name") String name, @RequestParam Integer age,
                                     @RequestParam Map<String, String> params) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("age", age);
        map.put("params", params);
        return map;
    }
    

    请求地址 http://localhost:8080/show?name=tinyspot&age=20

    1.2 @RequestAttribute

    required = false 表示不是必须的

    @GetMapping("/show")
    public Map<String, Object> show(@RequestAttribute(value = "name", required = false) String name, HttpServletRequest request) {
    }
    

    2. @PathVariable

    • 获取 URL 上的值

    请求URL:http://localhost:8080/path/tinyspot/1001

    @RequestMapping("/path/{name}/{code}")
    public Map<String, Object> path(@PathVariable String name, @PathVariable String code,
                                    @PathVariable Map<String, String> kv) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("code", code);
        map.put("kv", kv);
        return map;
    }
    

    打印结果 {"code":"1001","name":"tinyspot","kv":{"code":"1001","name":"tinyspot"}}

    3. @RequestHeader

    @RequestMapping("/header/{name}/{code}")
    public Map<String, Object> header(@RequestHeader("user-agent") String userAgent, 
                                      @RequestHeader Map<String, String> header) {
        Map<String, Object> map = new HashMap<>();
        map.put("userAgent", userAgent);
        map.put("header", header);
        return map;
    }
    

    4. @CookieValue

    @RequestMapping("/user/cookie")
    public Map<String, Object> cookie(@CookieValue("Idea-42dd4fb8") String value, @CookieValue("Idea-42dd4fb8") Cookie cookie) {
        Map<String, Object> map = new HashMap<>();
        map.put("value", value);
        map.put("cookie", cookie);
        return map;
    }
    

    5. @RequestBody

    <form action="/save" method="post">
        用户名:<input name="userName" /> <br>
        邮箱:<input name="email" /> <br>
        <input type="submit" value="save" >
    </form>
    

    获取请求体的数据

    @PostMapping("/save")
    public Map<String, Object> save(@RequestBody String content) {
        Map<String, Object> map = new HashMap<>();
        map.put("content", content);
        return map;
    }
    

    参数自动封装

    @RequestMapping("/show")
    public String show(User user) {
        return "";
    }
    

    6. 矩阵变量 @MatrixVariable

    6.1 请求示例

    <a href="/matrix/user;name=tinyspot;job=java,c++">/matrix/{path;k=key;v=value1,value2}</a> <br>
    <a href="/matrix/user;name=tinyspot;job=java;job=c++">/matrix/{path;k=key,v=value1,v=value2}</a> <br>
    
    // 矩阵变量必须有 url 路径变量才能被解析
    @RequestMapping("/matrix/{path}")
    public Map<String, Object> matrix(@PathVariable String path,
                                      @MatrixVariable("name") String name, @MatrixVariable("job") List<String> jobs) {
        Map<String, Object> map = new HashMap<>();
        map.put("path", path);
        map.put("name", name);
        map.put("jobs", jobs);
        return map;
    }
    

    6.2 请求实例2

    <a href="/matrix2/animal;name=AAA/type;name=BBB">/matrix2/{category}/{type}</a>

    @GetMapping("/matrix2/{category}/{type}")
    public Map<String, Object> matrix2(@MatrixVariable(value = "name", pathVar = "category") String category,
                                       @MatrixVariable(value = "name", pathVar = "type") String type) {
        Map<String, Object> map = new HashMap<>();
        map.put("category", category);
        map.put("type", type);
        return map;
    }
    

    6.3 开启矩阵变量

    • spring boot 默认禁用矩阵变量

    方式一:@Configuration + WebMvcConfigurer

    @Configuration
    public class WebConfig implements WebMvcConfigurer {
        @Override
        public void configurePathMatch(PathMatchConfigurer configurer) {
            UrlPathHelper urlPathHelper = new UrlPathHelper();
            // 不移除 ; 后面的内容,使矩阵变量生效
            urlPathHelper.setRemoveSemicolonContent(false);
            configurer.setUrlPathHelper(urlPathHelper);
        }
    }
    

    方式二:直接使用 WebMvcConfigurer

    @Configuration
    public class WebMVCConfig {
        @Bean
        public WebMvcConfigurer webMvcConfigurer() {
            return new WebMvcConfigurer() {
                @Override
                public void configurePathMatch(PathMatchConfigurer configurer) {
                    UrlPathHelper urlPathHelper = new UrlPathHelper();
                    urlPathHelper.setRemoveSemicolonContent(false);
                    configurer.setUrlPathHelper(urlPathHelper);
                }
            };
        }
    }
    

    6.4 源码解析

    public class WebMvcAutoConfiguration {
        public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer, ServletContextAware {
            public void configurePathMatch(PathMatchConfigurer configurer) {
                UrlPathHelper urlPathHelper = new UrlPathHelper();
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:Spring Boot Web 请求参数之注解

        本文链接:https://www.haomeiwen.com/subject/fttlfdtx.html