美文网首页技术SpringBoot之路程序员
Spring Boot之路[7]--请求参数绑定

Spring Boot之路[7]--请求参数绑定

作者: BeeNoisy | 来源:发表于2016-09-15 10:15 被阅读3788次

    本文预计需要5分钟阅读

    专题简介

    SpringBoot之路专题是一个记录本人在使用Spring和SpringBoot相关技术中所遇到的问题和要解决的问题。每用到一处知识点,就会把这处知识补充到Github一个对应的分支上。会以专题的方式,力争每一篇博客,由浅入深,把每个知识点讲解到实战级别,并且分析Spring源码。整个项目会以一个开发一个博客系统为最终目标,每一个分支都记录着一步一步搭建的过程。与大家分享,代码会同步发布到这里

    本节简介

    请求参数是指发起的请求中的请求参数,如www.xxx.com?name=beenoisy&age=20中,name就是参数,而参数值为beenoisy,多个参数之间使用&连接。

    超文本传输协议(HTTP)的统一资源定位符将从因特网获取信息的五个基本元素包括在一个简单的地址中:
    传送协议。

    源码

    package com.beenoisy.springboot.way.controller;
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.HashMap;
    import java.util.Map;
    
    @RestController// 1
    @RequestMapping(value = "article") // 2
    public class ArticleController {
    
        @RequestMapping(method = RequestMethod.GET) // 3
        public Map<String, String> getArticle(
                @RequestParam("id") int id// 4
        ) {
            Map<String, String> result = new HashMap<>();           // 5
            result.put("title", "this is article of id " + id);     // 5
            result.put("content", "this is article of id " + id);   // 5
            return result;
        }
    }
    
    
    1. 添加@RestController,表明这是一个controller。RestController相当于同时添加了ResponseBody和Controller
    2. 将/article的url路径映射到这个Controller
    3. 将Get方法映射到这个方法
    4. 接受名为id的参数,使用@RequestParam,对参数名称进行绑定。这里多说一句,常见的参数,spring-boot都能提供很好的参数绑定。比如Map,Integer,Boolean,甚至是xml。下一节将介绍如何自定义绑定方式。将参数绑定到一个自定义对象上。
    5. 构造返回数据

    运行截图

    运行截图

    这里使用了JSON Viewer插件来对返回json进行格式化和染色。

    最后,源码放在这里:

    https://github.com/jacks808/spring-boot-way/tree/07-param-binding
    如果文章内容对你有帮助,欢迎在github上star或点赞。

    相关文章

      网友评论

      本文标题:Spring Boot之路[7]--请求参数绑定

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