Springboot data binding

Programmer light 2022-02-13 07:52:43 阅读数:689

springboot data binding

Model

You must know Model class , In the controller , The data will be stored in Model In the object , When you need to generate HTML When , The template engine locates the data by name , Like the picture below .

@RequestMapping("/model")
public String model(Model model){
model.addAttribute("hobbies", Arrays.asList(" skiing "," Trampoline "," Skate "," surfing "));
return "model";
}

In a broad sense ,Model refer to MVC Medium M, namely Model( Model ). In a narrow sense ,Model That's it. key-value aggregate . actually , Upper figure model Method derived model The object is a java.util.Map , You can take Model Replace the type with Map<String, Object> , perhaps ModelMap—— One implemented Model Interface java.util.HashMap.

Go to Model There is another way to put data in , Use ModelAndView. Just like its name ,ModelAndView take Model Bound with the view name , As the return value of the request processing method .

Model Implementation class of :BindingAwareModelMap

ModelAndView

How to determine the writing method , Everyone is different , As long as your choice is consistent in the project .

One 、 The basic pattern

1、 Basic data type ( With int For example )

stay controller Write a int Parameter binding method

@GetMapping("/getInt")
public String getInt(int id){
return "ID = " + id;
}
@RunWith(SpringRunner.class)
@WebMvcTest
public class DataBindGetRequestControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void getInt() throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.put("id", Collections.singletonList("100"));
params.put("name",Collections.singletonList(" Zhang San "));
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/getInt").params(params).accept(MediaType.APPLICATION_JSON);
ResultActions resultActions = mockMvc.perform(requestBuilder);
resultActions.andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print());
}
}

summary :

1) When binding parameters with basic types , You have to pass in key value , And value Value must be a declared base type , If the data submitted on the page is null or “” Data conversion exceptions will occur , Therefore, it is best to use the packing type parameter

2) Front end parameter name and controller Data binding can be completed when the parameter names of are consistent , Inconsistencies can be used

postman request

@RequestParam

@GetMapping("/getInt2")
public String getInt2(@RequestParam(value = "ik") int id){
return "IK = " + id;
}

2、 Packing type parameter binding

stay controller Write the method of binding multiple wrapper type parameters in

@RequestMapping("/getPackType")
@ResponseBody
public String getPackType(String name,Long id){
return "name = " + name + " id = " + id;
}
@Test
public void getPackType() throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.put("name",Collections.singletonList(" Zhang San "));
params.put("id",Collections.singletonList("1000"));
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/getPackType").params(params).accept(MediaType.APPLICATION_JSON);
ResultActions resultActions = mockMvc.perform(requestBuilder);
resultActions.andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print());
}

summary :

1) When binding parameters with wrapper type, it is the same as the basic data type , Transmitted key The value should be consistent with the parameter name bound inside

2) When binding a parameter to a wrapper type, the value of the parameter may not be passed to null, It can also be empty

3、 Custom object type parameter binding

@RequestMapping("/getUser")
@ResponseBody
public User getUser(User user){
return user;
}
 @Test
public void getUser() throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.put("id",Collections.singletonList("1000"));
params.put("userName",Collections.singletonList(" Li Si "));
MockHttpServletRequestBuilder requestBuilder =
MockMvcRequestBuilders.get("/getUser").params(params).accept(MediaType.APPLICATION_JSON);
ResultActions resultActions = mockMvc.perform(requestBuilder);
resultActions.andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print());
}

summary :1) Just match the property name of the object with the property name of the front end input The parameter names of the are consistent

4、 Custom composite object type parameter binding

@Data
public class OrderForm {
private Long id;
private String orderSN;
private List<Goods> goods;
}
@Data
public class Goods {
private Long id;
private String goodsName;
}
@RequestMapping(value = "/getOrderForm",produces = "application/json;charset=utf-8")
@ResponseBody
public OrderForm getOrderForm(OrderForm orderForm){
return orderForm;
}
@Test
public void getOrderForm() throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.put("id",Collections.singletonList("1000"));
params.put("orderSN",Collections.singletonList(UUID.randomUUID().toString()));
params.put("goods[0].id",Collections.singletonList("1000"));
params.put("goods[0].goodsName",Collections.singletonList(" Apple mobile phone "));
params.put("goods[1].id",Collections.singletonList("2000"));
params.put("goods[1].goodsName",Collections.singletonList(" Huawei mobile phones "));
MockHttpServletRequestBuilder requestBuilder =
MockMvcRequestBuilders.get("/getOrderForm").params(params).accept(MediaType.APPLICATION_JSON);
ResultActions resultActions = mockMvc.perform(requestBuilder);
resultActions.andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print());
}

summary :

1) Custom composite object types are used in the same way as custom object types

2) Custom composite object types input The parameter name of should use “ Property name ( Properties of the object type ). Property name " Named after the

5、List Parameter binding

@RequestMapping("/listIds")
@ResponseBody
public List<Long> listIds(@RequestParam List<Long> ids){
return ids;
}
@Test
public void listIds() throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.put("ids",Collections.singletonList("1,2,3"));
MockHttpServletRequestBuilder requestBuilder =
MockMvcRequestBuilders.get("/listIds").params(params).accept(MediaType.APPLICATION_JSON);
ResultActions resultActions = mockMvc.perform(requestBuilder);
resultActions.andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print());
}
// If not @RequestParam("ids")
//No primary or single unique constructor found for interface java.util.List

summary :

1) Front end transfers are separated by commas

6、 Receive array parameters

@RequestMapping("/arrIds")
@ResponseBody
public String[] arrIds(@RequestParam String[] ids){
return ids;
}
@Test
public void arrIds() throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.put("ids",Collections.singletonList("1,2,3"));
MockHttpServletRequestBuilder requestBuilder =
MockMvcRequestBuilders.get("/arrIds").params(params).accept(MediaType.APPLICATION_JSON);
ResultActions resultActions = mockMvc.perform(requestBuilder);
resultActions.andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print());
}

summary :

1) Front end transfers are separated by commas

7、Map Parameter binding

@RequestMapping(value = "/getMap")
@ResponseBody
public Map<String,Object> getMap(@RequestParam Map<String,Object> map){
return map;
}
@Test
public void getMap() throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.put("id",Collections.singletonList("123"));
params.put("name",Collections.singletonList(" Little black "));
params.put("price",Collections.singletonList("500"));
MockHttpServletRequestBuilder requestBuilder =
MockMvcRequestBuilders.get("/getMap").params(params).accept(MediaType.APPLICATION_JSON);
ResultActions resultActions = mockMvc.perform(requestBuilder);
resultActions.andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print());
}

summary :

1) need RequestParam annotation

8、@RequestParam Annotation analysis

@RequestParam The function of annotation is limited by parameters 、 Set parameter defaults 、 Custom parameter name

1). Parameter limits ( You can use required=false close )

@RequestMapping(value = "/getName",produces = {"application/json;charset=utf-8"})
@ResponseBody
public String getName(@RequestParam(required = false,defaultValue = " Laugh ") String name){
return name;
}
@Test
public void getName() throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.put("name",Collections.singletonList(" Little black "));
MockHttpServletRequestBuilder requestBuilder =
MockMvcRequestBuilders.get("/getName").params(params).accept(MediaType.APPLICATION_JSON);
ResultActions resultActions = mockMvc.perform(requestBuilder);
resultActions.andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print());
}

2) Set parameter defaults

@GetMapping("/defaultValue")
public Integer defaultValue(@RequestParam(defaultValue = "100") Integer num){
return num;
}

3) Custom parameter name


@RequestMapping(value = "/defaultValue",produces = {"application/json;charset=utf-8"})
@ResponseBody
public Integer defaultValue(@RequestParam(defaultValue = "100",name = "goods") Integer num){
return num;
}

summary :

1)@RequestParam Annotation settings change parameter names 、 Set parameter limits and set parameter defaults , It can be used according to different scenarios

2)@RequestParam You can use multiple

Two 、Json Mode parameter binding

Due to the separation of front and rear ends and the diversity of front ends , Usually we use json Data format parameters / Data transfer , Speaking of json Format , You have to say @RequestBody, This is the use of Json Pattern is an essential part of parameter binding

1、@RequestBody Annotation analysis

1)@RequestBody The role of annotations will be json Format data to java object

2)@RequestBody It is often used to deal with application/json type

3)@RequestBody It received a json Format string

2、 Basic data type ( With int For example )

@RequestMapping(value = "/postInt",method = RequestMethod.POST)
@ResponseBody
public int postInt(int id){
return id;
}

@RunWith(SpringRunner.class)
@WebMvcTest
public class DataBindPostRequestControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void postInt() throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.put("id", Collections.singletonList("100"));
MockHttpServletRequestBuilder mockHttpServletRequestBuilder =
MockMvcRequestBuilders.post("/postInt")
.params(params)
.accept(MediaType.APPLICATION_JSON);
ResultActions resultActions = mockMvc.perform(mockHttpServletRequestBuilder);
resultActions.andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print());
}
}

3、json The mode is directly bound to the user-defined object type

@RequestMapping(value = "/postUser",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public User postUser(@RequestBody User user){
return user;
}
 @Test
public void postUser() throws Exception {
Map<String,Object> params = new HashMap<>();
params.put("id", "100");
params.put("userName", " Zhang San ");
MockHttpServletRequestBuilder mockHttpServletRequestBuilder =
MockMvcRequestBuilders.post("/postUser")
.content(JSONObject.toJSONString(params))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON);
ResultActions resultActions = mockMvc.perform(mockHttpServletRequestBuilder);
resultActions.andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print());
}

summary :

1) direct json The string is converted to javaBean, But the front-end transmission must be json Formatted data

2) The parameter name must always be the same as the attribute name defined by the entity class to get the parameter correctly

 

4、json Custom object direct binding mode

@RequestMapping(value = "/postOrderForm",method = RequestMethod.POST,produces = {"application/json;charset=utf-8"})
@ResponseBody
public OrderForm postOrderForm(@RequestBody OrderForm orderForm){
return orderForm;
}

@Test
public void postOrderForm() throws Exception {
OrderForm orderForm = new OrderForm();
orderForm.setId(1000L);
orderForm.setOrderSN(UUID.randomUUID().toString());
Goods g1 = new Goods();
g1.setId(1000L);
g1.setGoodsName(" Apple mobile phone ");
Goods g2 = new Goods();
g2.setId(2000L);
g2.setGoodsName(" Huawei mobile phones ");
List<Goods> goodsList = new ArrayList<>();
goodsList.add(g1);
goodsList.add(g2);
orderForm.setGoods(goodsList);
MockHttpServletRequestBuilder mockHttpServletRequestBuilder =
MockMvcRequestBuilders.post("/postOrderForm")
.content(JSONObject.toJSONString(orderForm))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON);
ResultActions resultActions = mockMvc.perform(mockHttpServletRequestBuilder);
resultActions.andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print());
}

 

 

summary :

1) Both require the parameter name to be consistent with the attribute name defined by the entity class

2) Direct access , The parameter name of the hierarchy needs to be . Appoint ;@RequestBody Formal parameters json The format needs to be nested

5、json Pattern binding array type ( Generally used for batch operation )

controller Use @RequestBody+List Receive array ( recommend )

@RequestMapping("/postIds")
@ResponseBody
public List<Integer> postIds(@RequestBody List<Integer> ids){
return ids;
}

@Test
public void postIds() throws Exception {
List<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
ids.add(3);
MockHttpServletRequestBuilder mockHttpServletRequestBuilder =
MockMvcRequestBuilders.post("/postIds")
.content(JSONObject.toJSONString(ids))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON);
ResultActions resultActions = mockMvc.perform(mockHttpServletRequestBuilder);
resultActions.andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print());
}

summary :

1)@RequestBody obtain List Array type parameters are widely used

2) Later, you can list The content in the is transformed into String type , With "," Division

6、json Pattern binding multiple objects ( Same parameter type )

1) Use List<E> obtain

@RequestMapping(value = "/postOrderForms",method = RequestMethod.POST,produces = {"application/json;charset=utf-8"})
@ResponseBody
public List<OrderForm> postOrderForms(@RequestBody List<OrderForm> orderForms){
return orderForms;
}

 

@Test
public void postOrderForms() throws Exception {
List<OrderForm> orderForms = new ArrayList<>();
OrderForm orderForm = new OrderForm();
orderForm.setId(1000L);
orderForm.setOrderSN(UUID.randomUUID().toString());
Goods g1 = new Goods();
g1.setId(1000L);
g1.setGoodsName(" Apple mobile phone ");
Goods g2 = new Goods();
g2.setId(2000L);
g2.setGoodsName(" Huawei mobile phones ");
List<Goods> goodsList = new ArrayList<>();
goodsList.add(g1);
goodsList.add(g2);
orderForm.setGoods(goodsList);
OrderForm orderForm1 = new OrderForm();
orderForms.add(orderForm);
MockHttpServletRequestBuilder mockHttpServletRequestBuilder =
MockMvcRequestBuilders.post("/postOrderForms")
.content(JSONObject.toJSONString(orderForms))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON);
ResultActions resultActions = mockMvc.perform(mockHttpServletRequestBuilder);
resultActions.andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print());
}

 

 

2) Use Map<String,Object> receive

@RequestMapping("/postMapOrderForm")
@ResponseBody
public Map<String,OrderForm> postMapOrderForm(@RequestBody Map<String,OrderForm> map){
return map;
}
@Test
public void postMapOrderForm() throws Exception {
Map<String,OrderForm> map = new HashMap<>();
OrderForm orderForm = new OrderForm();
orderForm.setId(1000L);
orderForm.setOrderSN(UUID.randomUUID().toString());
Goods g1 = new Goods();
g1.setId(1000L);
g1.setGoodsName(" Apple mobile phone ");
Goods g2 = new Goods();
g2.setId(2000L);
g2.setGoodsName(" Huawei mobile phones ");
List<Goods> goodsList = new ArrayList<>();
goodsList.add(g1);
goodsList.add(g2);
orderForm.setGoods(goodsList);
map.put("orderForm",orderForm);
MockHttpServletRequestBuilder mockHttpServletRequestBuilder =
MockMvcRequestBuilders.post("/postMapOrderForm")
.content(JSONObject.toJSONString(map))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON);
ResultActions resultActions = mockMvc.perform(mockHttpServletRequestBuilder);
resultActions.andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print());
}

copyright:author[Programmer light],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130752403978.html