springboot在controller中传递参数


    header-->放在请求头。请求参数的获取:@RequestHeader(代码中接收注解)
    query -->用于get请求的参数拼接。请求参数的获取:@RequestParam(代码中接收注解)
    path -->(用于restful接口)-->请求参数的获取:@PathVariable(代码中接收注解)
    body -->放在请求体。请求参数的获取:@RequestBody(代码中接收注解)
    form -->(不常用)

一.@PathVariable

@RequestMapping(value="/user/{username}")
    public String userProfile(@PathVariable(value="username") String username) {
        return "user"+username;
    }

或者

@RequestMapping(value = "/user/{username}/blog/{blogId}")
    public String getUserBlog(@PathVariable String username, @PathVariable int blogId) {
        return "user:" + username + "blog->" + blogId;
    }

二.@RequestParam

?key1=value1&key2=value2这样的参数列表。通过注解@RequestParam可以轻松地将URL中的参数绑定到处理函数方法的变量中

@RequestMapping(value="/user")
    public String getUserBlog(@RequestParam(value="id") int blogId) {
        return "blogId="+blogId;
    }

当然,在参数不存在的情况下,可能希望变量有一个默认值:

@RequestParam(value = "id", required = false, defaultValue = "0")

三.@RequestBody

1.接收的参数来自于requestBody中,即请求体中
2.@RequestBody注解可以将json数据解析然后供后端使用
3.使用实体类VO进行接收数据

/**
      * Post使用@RequestBody注解将Json格式的参数自动绑定到Entity类
      * @param order
      * @return
*/
@PostMapping("/order/check")
public String checkOrder(@RequestBody Order order){
String result="id:"+order.getId()+",name:"+order.getName()+",price:"+order.getPrice();
        return result;
     }

四、@ModelAttribute

@ModelAttribute也可以使用实体类VO进行接收数据,区别在于:

1.使用@ModelAttribute注解的实体类接收前端发来的数据格式需要为"x-www-form-urlencoded",

2.@RequestBody注解的实体类接收前端的数据格式为JSON(application/json)格式。

(若是使用@ModelAttribute接收application/json格式,虽然不会报错,但是值并不会自动填入

@RequestMapping(value = "sumByWoType")
    @GetMapping
    @ApiOperation("sumByWoType")
    public JSONObject sumByWoType(@ModelAttribute WOTypeQueryParam woTypeQueryParam) {
        String paramUrl = woTypeQueryParam.toString();
        String url = String.format("%s/%s?%s", workOrderUrlConfig.getUrl(), WorkOrderConstant.SUM_BY_WO_TYPE, paramUrl);
        System.out.println(url);
        return null;
        
}

五、@RequestHeader

@Controller
public class handleHeader {

    @GetMapping("/getHeader")
    public String getRequestHeader(@RequestHeader("User-Agent") String agent) {
        System.out.println(agent);
        return "success";
    }

}

六、@CookieValue

@CookieValue接收cookie的值

public String test(@CookieValue(value="JSESSIONID", defaultValue="") String sessionId) {
}

 七、@SessionAttributes绑定命令对象到session

转自:https://www.cnblogs.com/penghq/p/13049393.html

posted @ 2021-05-12 17:17  Mars.wang  阅读(2501)  评论(0编辑  收藏  举报