Spring MVC @RequestParam (5)

Source: Internet
Author: User

Case to illustrate
1 @RequestMapping ("User/add") publicstring Add (@RequestParam ("name") of string name,int age ) {4 System.out.println (name+ "," + Age);  Return "Hello";  6}         

Test 1

When we request the path to: http://localhost:8080/springmvc-1/user/add?name=caoyc&age=18

Output Result: caoyc,18

Test 2

When I request the path to: http://localhost:8080/springmvc-1/user/add?age=18

Output: An exception occurred. It means you have to have this parameter.

Solution: Add a required=false in the @requestparam tag to indicate that the property is not required

1 @RequestParam (value= "name", required=false)

Output Result: null,18

Test 3

When I request the path to: Http://localhost:8080/springmvc-1/user/add?name=caoyc

The same exception appears above

Then according to the method set above

1 @RequestParam (value= "age", required=int age

The result runs again. or throw an exception

It's very clear here, probably meaning that you can't say a null value is assigned to age. Package type should be used

Then we change the code to this:

1 @RequestParam (value= "age", required=false) Integer age

Result correct output: caoyc,null

There is another way to change this: Specify a default value for the parameter

1 @RequestParam (value= "age", required=int age

Result output: caoyc,0

"Summary" corresponds to the parameters of the @requestparam basic type we'd better use the packing type.

and a note of acquaintance.@RequestHeader. Use the same way as @requestparam. It's not a long explanation here.

Spring MVC @RequestParam (5)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.