為了使數(shù)據(jù)綁定模型自定義在表單數(shù)據(jù)和 JSON 之間保持一致,Micronaut 使用 Jackson 從表單提交中實(shí)現(xiàn)綁定數(shù)據(jù)。
這種方法的優(yōu)點(diǎn)是用于自定義 JSON 綁定的相同 Jackson 注釋可用于表單提交。
實(shí)際上,這意味著要綁定常規(guī)表單數(shù)據(jù),對(duì)先前 JSON 綁定代碼所需的唯一更改是更新使用的 MediaType:
將表單數(shù)據(jù)綁定到 POJO
Java |
Groovy |
Kotlin |
@Controller("/people")
public class PersonController {
Map<String, Person> inMemoryDatastore = new ConcurrentHashMap<>();
@Post
public HttpResponse<Person> save(@Body Person person) {
inMemoryDatastore.put(person.getFirstName(), person);
return HttpResponse.created(person);
}
}
|
@Controller("/people")
class PersonController {
Map<String, Person> inMemoryDatastore = new ConcurrentHashMap<>()
@Post
HttpResponse<Person> save(@Body Person person) {
inMemoryDatastore.put(person.getFirstName(), person)
HttpResponse.created(person)
}
}
|
@Controller("/people")
class PersonController {
internal var inMemoryDatastore: MutableMap<String, Person> = ConcurrentHashMap()
@Post
fun save(@Body person: Person): HttpResponse<Person> {
inMemoryDatastore[person.firstName] = person
return HttpResponse.created(person)
}
}
|
為避免拒絕服務(wù)攻擊,綁定期間創(chuàng)建的集合類(lèi)型和數(shù)組受配置文件(例如 application.yml)中的設(shè)置 jackson.arraySizeThreshold 限制
或者,除了使用 POJO,您還可以將表單數(shù)據(jù)直接綁定到方法參數(shù)(這也適用于 JSON?。?
將表單數(shù)據(jù)綁定到參數(shù)
Java |
Groovy |
Kotlin |
@Controller("/people")
public class PersonController {
Map<String, Person> inMemoryDatastore = new ConcurrentHashMap<>();
@Post("/saveWithArgs")
public HttpResponse<Person> save(String firstName, String lastName, Optional<Integer> age) {
Person p = new Person(firstName, lastName);
age.ifPresent(p::setAge);
inMemoryDatastore.put(p.getFirstName(), p);
return HttpResponse.created(p);
}
}
|
@Controller("/people")
class PersonController {
Map<String, Person> inMemoryDatastore = new ConcurrentHashMap<>()
@Post("/saveWithArgs")
HttpResponse<Person> save(String firstName, String lastName, Optional<Integer> age) {
Person p = new Person(firstName, lastName)
age.ifPresent({ a -> p.setAge(a)})
inMemoryDatastore.put(p.getFirstName(), p)
HttpResponse.created(p)
}
}
|
@Controller("/people")
class PersonController {
internal var inMemoryDatastore: MutableMap<String, Person> = ConcurrentHashMap()
@Post("/saveWithArgs")
fun save(firstName: String, lastName: String, age: Optional<Int>): HttpResponse<Person> {
val p = Person(firstName, lastName)
age.ifPresent { p.age = it }
inMemoryDatastore[p.firstName] = p
return HttpResponse.created(p)
}
}
|
正如您從上面的示例中看到的那樣,這種方法允許您使用諸如支持 Optional 類(lèi)型和限制要綁定的參數(shù)等功能。使用 POJO 時(shí),您必須小心使用 Jackson 注釋來(lái)排除不應(yīng)綁定的屬性。
更多建議: