@RequestParam annotation parsing

There are two main ways to get parameters in the spring MVC background control layer: one is request.getParameter("...

There are two main ways to get parameters in the spring MVC background control layer: one is request.getParameter("name"), the other is to get parameters directly with the annotation @ RequestParam. Here's the main comment

1, Basic use, get submitted parameters
Back end code:
Java code collection code

@RequestMapping(path = { "/list" }, method = RequestMethod.GET) public String listUser(@RequestParam(defaultValue = "1", required = false) Integer pageIndex, Model model,String keyWord, UserSerachEnum type, @RequestParam(defaultValue = "user", required = false) String folder) { .... }

Front end code:
Html code collection code

<tr> <td><img src='<c:url value="/upload/$.png"></c:url>' style="width: 100px; height: 100px"></td> <td>$</td> <td>$</td> <td><a href='<c:url value="/user/update?id=$"></c:url>'>modify</a> &emsp; <a href='<c:url value="/user/remove?id=$"></c:url>'>delete</a></td> </tr>

Front end interface:

Execution result:
test1
123

You can see that spring will automatically enter by encapsulating the parameter name. We can use the parameter name directly

2, Handling of various abnormal situations
1. You can specify a parameter name for the incoming parameter
Java code collection code

@RequestParam String inputStr // The following parameter is specified as aa. If the front end does not pass the aa parameter name, an error will be reported @RequestParam(value="aa") String inputStr

Error message:
HTTP Status 400 - Required String parameter 'aa' is not present

2. You can ask whether the front-end parameters configured by @ RequestParam must be passed through required=false or true
Java code collection code

// If required=false, the parameter will be given a value of null. If required=true, there must be @RequestMapping("testRequestParam") public String filesUpload(@RequestParam(value="aa", required=true) String inputStr, HttpServletRequest request)

3. If the parameter annotated with @ RequestMapping is of int basic type, but required=false, an error will be reported if the parameter value is not passed, because if the value is not passed, the value will be assigned as null to int, which is not allowed
Java code collection code

@RequestMapping("testRequestParam") public String filesUpload(@RequestParam(value="aa", required=true) String inputStr, @RequestParam(value="inputInt", required=false) int inputInt ,HttpServletRequest request) { // ... omitted return "index"; }

16 May 2020, 10:51 | Views: 7682

Add new comment

For adding a comment, please log in
or create account

0 comments