搜索
您的当前位置:首页正文

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

来源:二三娱乐

本文预计需要5分钟阅读

专题简介

本节简介

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

  • 服务器。(通常为,有时为)
  • 端口号。(以数字方式表示,若为HTTP的预设值“:80”可省略)
  • 路径。(以“/”字元区别路径中的每一个目录名称)
  • 查询。(GET模式的表单参数,以“?”字元为起点,每个参数以“&”隔开,再以“=”分开参数名称与资料,通常以UTF8的URL编码,避开字元冲突的问题)
    引自维基百科:

源码

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进行格式化和染色。

最后,源码放在这里:

Top