SpringBoot获取URL中的数据(@PathVariable)和请求的参数(@RequestParam)

背景:为了更好的测试,你就得更好地了解开发,为了更好的了解开发,你就知道开发常用框架,那就来吧,第一个springboot
目的:使用不同yaml文件配置不同的环境
组网图:不涉及
工具:java version “1.8.0_65” ;Apache Maven 3.6.3;IDEA版本 2018.3 (准备步骤见本人其它博文)
步骤:
SpringBoot获取URL中的数据和请求的参数,有两种方式,
一种是:@PathVariable,获取URL中的参数
另一种是:@RequestParam,获取请求参数值
第一种:@PathVariable

package com.hua.myfirst;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//@Controller + @Responsebody =@ RestController
@RestController
@RequestMapping("/test")
public class HelloConteoller {

    @Autowired
    private WomanConfig womanConfig;

    //不同的链接访问同一个接口
    @GetMapping("/hello/{id}")
    public String hello(@PathVariable("id") Integer id) {
        return "id:" + id ;
    }

}

启动成功,
打开链接:http://127.0.0.1:8080/v1/test/hello/100
SpringBoot获取URL中的数据(@PathVariable)和请求的参数(@RequestParam)_第1张图片

第二种:@RequestParam

package com.hua.myfirst;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

//@Controller + @Responsebody =@ RestController
@RestController
@RequestMapping("/test")
public class HelloConteoller {

    @Autowired
    private WomanConfig womanConfig;

    //不同的链接访问同一个接口
    @GetMapping("/hello")
    public String hello(@RequestParam("id") Integer id) {
        return "id:" + id ;
    }

}

启动成功,
打开链接:http://127.0.0.1:8080/v1/test/hello?id=100
SpringBoot获取URL中的数据(@PathVariable)和请求的参数(@RequestParam)_第2张图片
@RequestParam进阶:
使用@RequestParam(value = “id”, required = false, defaultValue = "0"设置非必填参数,以及默认值

package com.hua.myfirst;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

//@Controller + @Responsebody =@ RestController
@RestController
@RequestMapping("/test")
public class HelloConteoller {

    @Autowired
    private WomanConfig womanConfig;

    //不同的链接访问同一个接口
    @GetMapping("/hello")
    public String hello(@RequestParam(value = "id", required = false, defaultValue = "0") Integer myID) {
        return "id:" + myID ;
    }

}

启动成功,
打开链接:http://127.0.0.1:8080/v1/test/hello 默认值为0
SpringBoot获取URL中的数据(@PathVariable)和请求的参数(@RequestParam)_第3张图片

你可能感兴趣的:(java学习)