springBoot入门之多种配置URL的方法

1.无参传递

package com.example.learn;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/*
演示各种传参形式
 */
@RestController
public class ParaController {
    @GetMapping("/firstrequest")
    public String firstRequest(){
        return "第一个Spring Boot接口";
    }
}

效果
1.png

2.变量参数的接收

package com.example.learn;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ParaController {
    @GetMapping("/requestpara")//接受传递的参数
    public String requestpara(@RequestParam Integer num){
        return "para from request:"+num;//输出传递的参数
    }
}

效果图:
2.png

3.URL中传递参数

package com.example.learn;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ParaController {
    @GetMapping("/para/{num}")//接受URL中传递的参数
    public String pathpara(@PathVariable Integer num){
        return "para from path:"+num;//输出传递的参数
    }
}

效果:
3.png

4.访问接口,添加公共前缀

@RequestMapping("pre")//设置统一前缀,访问时需加上/pre即可

5.多个接口对应一个方法

@GetMapping({"/multiurl1","/multiurl2"})//多URL使用{}包裹
public String multiurl(@RequestParam Integer num){
    return "para from request:"+num;
}

6.设置默认传参

@GetMapping("/required")//设置默认传参为0,必须带双引号包裹
public String required(@RequestParam(required = false,defaultValue = "0") Integer num){
    return "para from request:"+num;//输出传递的参数
}

效果图:

6.png
7.png

标签: SpringBoot

添加新评论