The use of Spring @RequestParam annotation

foreword

There are generally two types of data acquisition in the SpringMvc background.
1.request.getParameter("parameter name")
2. Get it with @RequestParam annotation

 

@RequestMapping("/")
public String Demo1(@RequestParam String lid){

    System.out.println("----"+lid);
    return null;
}

 

Front page

<input type="text" name="lid" /> <!-- Now the output is 10 -->

Console output interface

----10

springmvc will automatically inject according to the parameter name, so the name must be the same, otherwise it will not be injected

The parameter names do not match

@RequestMapping("/")
public String Demo1(@RequestParam(name="lid") String id){

    System.out.println("----"+id);
    return null;
}
Front page

<input type="text" name="lid" /> <!-- Now the output is 10 -->

Console output interface

----10

If the parameter names are inconsistent, you need to specify the parameter name after @RequestParam to assign values ​​to the following parameters.

set default value

@RequestMapping("/")
public String Demo1(@RequestParam(name="lid",defaultValue="ste") String id){

    System.out.println("----"+id);
    return null;
}
Front page



Console output interface

----you are

Precautions

@RequestMapping("/")
public String Demo1(@RequestParam(name="lid") int id){

    System.out.println("----"+id);
    return null;
}
Front page

<input type="text" name="lid" /> <!-- Now the output is 10 -->

Console output interface

----10

If you want @RequestParam to pass a value of int type data, if the front end does not input, then the int type data will be assigned null. Obviously, this is not allowed, and an error is reported directly.
You can use required=false or true to ask whether the front-end parameters configured by @RequestParam must be passed

// required=true, the parameter must be passed
@RequestMapping("/")
public String Demo1(@RequestParam(name="lid",required=true) int id){

    System.out.println("----"+lid);
    return null;
}`

If required is false, then the default value is null for the parameter

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324675486&siteId=291194637