@RequestParam和@GetMapping

@RequestParam

       @RequestParam可以接受简单类型的属性,也可以接受对象类型(如viewUserByBean方法)。创建一个实体类对象作为参数承载体,Spring MVC会根据参数名称自动将参数绑定到实体类对象的属性上,viewUserByBean就是这么处理的。

      value:String 类型,请求参数名,如viewUserByEachEle 方法中的userName表示请求参数名,它的值将被绑定到方法参数name。

      required:是否必须,默认值为true,表示请求参数中必须包含对应的参数,否则,将抛出400错误码;异常信息是org.springframework.web.bind.MissingServletRequestParameterException,提示“Required String parameter 'userName' is not present”。

      defaultValue:String 类型,表示如果请求中没有同名参数时的默认值,默认值可以是SpEL表达式,如“#{systemProperties['java.vm.version']}”。

      其实如果不使用@RequestParam,Spring MVC也会将request的parameter自动绑定到method的parameter中,使用@RequestParam只不过是对parameter进行配置和对URL更精确化的配置。例如,在请求参数名和方法参数名相同时,则可以省略@RequestParam注解。

@GetMapping 

       @GetMapping是一个组合注解,等价于@RequestMapping(method = RequestMethod.GET),它将HTTP Get请求映射到特定的处理方法上。例如,在测试用例中,使用@GetMapping("/testRequestParam")代替了@RequestMapping(value ="/viewUserByEachEle",method = RequestMethod.GET),显然,这可以精简我们的代码。

猜你喜欢

转载自www.cnblogs.com/zqzhen/p/12535918.html