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



SpringBoot获取URL中的数据和请求的参数,有两种方式,

一种是:@PathVariable,获取URL中的参数
另一种是:@RequestParam,获取请求参数值

@PathVariable和@RequestParam


@PathVariable是从路径里面去获取变量,也就是把路径当做变量。

 

@RequestParam是从请求里面获取参数。 

 

如:url:http://localhost:8080/test_mobile/test?a=777&b=888&c=999

 

如果你要得到?后面的参数(a、b、c)的值,则需要使用@RequestParam进行方法里参数的注解,当然springmvc默认的参数注解就是它。

 

例: @RequestMapping(value = "/test_mobile/test", method = RequestMethod.GET)
    public String list(Model model,@RequestParam String a) {  //当然可以不加,springmvc默认的
        System.out.println(a);
    }

 

如果“test_mobile”这个字符串需要后台获取到,使用@PathVariable

 

例:

@RequestMapping(value = "/{qqqqq}/test", method = RequestMethod.GET)
    public String list(Model model,@PathVariable("qqqqq") String aaaa) { 

 //这里只要满足value中的路径结构正确,注解后面保证名称一致,就可以得到{qqqqq}占位符所占的值。
        System.out.println(aaaa);
   }

第一种:@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

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

@RequestParam进阶:
使用@RequestParam(value = “id”, required = false, defaultValue = "0"设置非必填参数,以及默认值

//不同的链接访问同一个接口
    @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

posted on 2020-08-13 08:21 青蛙學堂 阅读(2015) 评论(0)  编辑 收藏 引用 所属分类: Java

只有注册用户登录后才能发表评论。
<2020年8月>
2627282930311
2345678
9101112131415
16171819202122
23242526272829
303112345

导航

统计

常用链接

留言簿(8)

随笔分类

随笔档案

收藏夹

青蛙学堂

最新评论

阅读排行榜

评论排行榜