SpringMVC 请求参数绑定之 @RequestParam

1. Overview

In this quick tutorial, we’ll explore Spring’s @RequestParam annotation.

Simply put, we can use @RequestParam to extract query parameters, form parameters and even files from the request.

We’ll discuss how to use @RequestParam and its attributes. We’ll also discuss the differences between @RequestParam and @PathVariable.

2. A Simple Mapping

Let’s say that we have an endpoint /api/foos that takes a query parameter called id:

1

2

3

4

5

@GetMapping("/api/foos")

@ResponseBody

public String getFoos(@RequestParam String id) {

    return "ID: " + id;

}

In this example, we used @RequestParam to extract the id query parameter.

A simple GET request would invoke getFoos:

1

2

3

http://localhost:8080/api/foos?id=abc

----

ID: abc

Next, let’s have a look at the annotation’s attributes: name, value, required anddefaultValue.

3. Specifying the Request Parameter Name

In the previous example, both variable name and the parameter name are the same.

Sometimes we want these to be different, though. Or, if we aren’t using Spring Boot, we may need to do special compile-time configuration or the parameter names won’t actually be in the bytecode.

But what’s nice is that we can configure the @RequestParam name using the nameattribute:

1

2

3

4

5

@PostMapping("/api/foos")

@ResponseBody

public String addFoo(@RequestParam(name = "id") String fooId, @RequestParam String name) {

    return "ID: " + fooId + " Name: " + name;

}

We can also do @RequestParam(value = “id”) or just @RequestParam(“id”).

4. Making an Optional Request Parameter

Method parameters annotated with @RequestParam are required by default.

This means that if the parameter isn’t present in the request, we’ll get an error:

1

2

3

4

GET /api/foos HTTP/1.1

-----

400 Bad Request

Required String parameter 'id' is not present

We can configure our @RequestParam to be optional, though, with the required attribute:

1

2

3

4

5

@GetMapping("/api/foos")

@ResponseBody

public String getFoos(@RequestParam(required = false) String id) {

    return "ID: " + id;

}

In this case, both:

1

2

3

http://localhost:8080/api/foos?id=abc

----

ID: abc

and

1

2

3

http://localhost:8080/api/foos

----

ID: null

will correctly invoke the method.

When the parameter isn’t specified, the method parameter is bound to null.

5. A Default Value for the Request Parameter

We can also set a default value to the @RequestParam by using the defaultValue attribute:

1

2

3

4

5

@GetMapping("/api/foos")

@ResponseBody

public String getFoos(@RequestParam(defaultValue = "test") String id) {

    return "ID: " + id;

}

This is like required=false, in that the user no longer needs to supply the parameter:

1

2

3

http://localhost:8080/api/foos

----

ID: test

Though, we are still okay to provide it:

1

2

3

http://localhost:8080/api/foos?id=abc

----

ID: abc

Note that when we set the defaultValue attribute, required is, indeed, set to false.

6. Mapping All Parameters

We can also have multiple parameters without defining their names or count by just using Map:

1

2

3

4

5

@PostMapping("/api/foos")

@ResponseBody

public String updateFoos(@RequestParam Map<String,String> allParams) {

    return "Parameters are " + allParams.entrySet();

}

Which will then reflect back any parameters sent:

1

2

3

curl -X POST -F 'name=abc' -F 'id=123' http://localhost:8080/api/foos

-----

Parameters are {[name=abc], [id=123]}

7. Mapping a Multi-Value Parameter

A single @RequestParam can have multiple values:

1

2

3

4

5

@GetMapping("/api/foos")

@ResponseBody

public String getFoos(@RequestParam List<String> id) {

    return "IDs are " + id;

}

And Spring MVC will map a comma-delimited id parameter:

1

2

3

http://localhost:8080/api/foos?id=1,2,3

----

IDs are [1,2,3]

Or a list of separate id parameters:

1

2

3

http://localhost:8080/api/foos?id=1&id=2

----

IDs are [1,2]

8. @RequestParam vs @PathVariable

@RequestParam and @PathVariable can both be used to extract values from the request URI, but they are a bit different.

8.1. Query Parameter vs URI Path

While @RequestParams extract values from the query string, @PathVariables extract values from the URI path:

1

2

3

4

5

@GetMapping("/foos/{id}")

@ResponseBody

public String getFooById(@PathVariable String id) {

    return "ID: " + id;

}

Then, we can map based on the path:

1

2

3

http://localhost:8080/foos/abc

----

ID: abc

And for @RequestParam, it will be:

1

2

3

4

5

@GetMapping("/foos")

@ResponseBody

public String getFooByIdUsingQueryParam(@RequestParam String id) {

    return "ID: " + id;

}

Which would give us the same response, just a different URI:

1

2

3

http://localhost:8080/foos?id=abc

----

ID: abc

8.2. Encoded vs Exact Value

Because @PathVariable is extracting values from the URI path, it’s not encoded. On the other hand, @RequestParam is.

Using the previous example, ab+c will return as-is:

1

2

3

http://localhost:8080/foos/ab+c

----

ID: ab+c

But for a @RequestParam request, the parameter is URL decoded:

1

2

3

http://localhost:8080/foos?id=ab+c

----

ID: ab c

8.3. Optional Values

Both @RequestParam and @PathVariable can be optional.

We can make @PathVariable optional by using the required attribute starting with Spring 4.3.3:

1

2

3

4

5

@GetMapping({"/myfoos/optional", "/myfoos/optional/{id}"})

@ResponseBody

public String getFooByOptionalId(@PathVariable(required = false) String id){

    return "ID: " + id;

}

Which, then, we can do either:

1

2

3

http://localhost:8080/myfoos/optional/abc

----

ID: abc

or:

1

2

3

http://localhost:8080/myfoos/optional

----

ID: null

For @RequestParam, we can also use the required attribute as we saw in a previous section.

Note that we should be careful when making @PathVariable optional, to avoid conflicts in paths.

9. Conclusion

In this article, we learned how to use @RequestParam and the difference between @RequestParam and @PathVariable.

The full source code for the examples can be found in the GitHub project.

 

补充一下:

还有一种直接封装到POJO(普通的java对象)的方式

 

 

class User{
    private String id;
    private String name;

    public User() { }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

 

1

2

3

4

5

@GetMapping("/api/foos")

@ResponseBody

public String getFoos(@RequestParam User user) {

    return  user;

}

1

2

3

http://localhost:8080/api/foos?id=abc&name=cde

----

user : {id : "abc", name : "cde"}

原文链接:https://www.baeldung.com/spring-request-param

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值