springboot幾種傳參方式

 

package com.steve.controller;

import com.steve.entity.User;
import org.springframework.web.bind.annotation.*;
import java.util.Map;

@RestController
public class HelloController {
    // 不帶參數         http://ip:port/test_no_param
    @RequestMapping("/test_no_param")
    public String testNoParam() {
        return "success";
    }
    // 帶有一個參數     http://ip:port/test_param?param=xxx
    @RequestMapping("/test_param")
    public String testParam(@RequestParam String param) {
        return "success, the param is: " + param;
    }
    // 帶多個參數      http://ip:port/test_multiple_param?name=xxx&password=zzz
    @RequestMapping("/test_multiple_param")
    public String testMultipleParam(@RequestParam String name, @RequestParam String password) {
        return "success, the name is: " + name + " password is: " + password;
    }
    // map接受參數     http://localhost:8081/test_param_map?key=ss&val=zz
    @RequestMapping("/test_param_map")
    public String testParamMap(@RequestParam Map map) {
        return "success, map: " + map;
    }
    // path參數       http://localhost:8081/test/aas
    @RequestMapping("/test/{path}")
    public String testPath(@PathVariable String path) {
        return "success, path: " + path;
    }
//----------------------- postman客戶端插件或者瀏覽器插件模擬   --------------------------
    // post帶一個參數   x-www-form-urlencoded的key-value對方式傳參
     //                 raw   json格式傳參            key爲time
    @PostMapping("/test_post_param")
    public String postParam(@RequestBody String time) {
        return "success, time: " + time;
    }
    // post帶Map參數     只能用raw   application/json格式傳參   key-value自定義
    @PostMapping("/test_post_map_param")
    public String postMapParam(@RequestBody Map map) {
        return "success, map: " + map;
    }
    // post轉實體對象   只能用raw   application/json格式傳參   key-value跟實體對應
    @PostMapping("/test_post_entity")
    public String postEntity(@RequestBody User user) {
        return "success, entity " + user;
    }
    //GET     http://localhost:8081/test_get    瀏覽器模擬
    @RequestMapping(value = "/test_get", method = RequestMethod.GET)
    public String testGetMethod() {
        return "get method";
    }
    @GetMapping("/test_get_method")
    public String testGet() {
        return "get method";
    }
    // POST      http://localhost:8081/test_post     postman模擬post請求
    @RequestMapping(value = "/test_post", method = RequestMethod.POST)
    public String testPostMethod() {
        return "post method";
    }
    @PostMapping("/test_post_method")
    public String testPost() {
        return "post method";
    }
}
public class User {

    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章