SpringMVC注解@RequestParam的作用及注意事項


一、作用

作用在方法傳遞的參數前,用於接收所傳參數

例如:http://localhost:8081/selectStudentById?id=01 接收問號后面的參數值(允許多個參數)

二、注解內部的四個屬性

1.name

指定傳入的參數名稱,其后面跟的參數名稱一定要與前端傳入的參數名稱一致

2.value

指定傳入的參數名稱,其后面跟的參數名稱一定要與前端傳入的參數名稱一致

3.requred

指定參數是否是必傳參數,如果不指定,默認為true

4.defaultValue

指定參數的默認值

注意:其中name和value屬性的作用等同的.其源碼中name的別名就是value,value的別名就是name

三、注意事項

1.@RequestParam可以解決前后端定義的參數名不一致的問題

例如前端傳入的參數名是name,后端方法接收的參數名是userName,這時可以通過@RequestParam指定value的值為name,實現name與userName的映射

  @RequestMapping(method = RequestMethod.GET, value = "selectCourseAndTeacherByStudent")
    public Course selectCourseAndCourseByStudent(@RequestParam(value = "name") String userName) {
        Course course = studentService.selectCourseAndTeacherByStudent(userName);
        return course;
    }

2.如果后端使用的是基本數據類型來接收參數,那么一定要設置required=false,並且要設置一個默認值

  @RequestMapping(method = RequestMethod.GET,value = "selectStudentById")
    public Student selectStudentById(@RequestParam(value = "id",required = false,defaultValue = "01") int id){
        return studentService.selectStudentById(id);
    }

因為考慮到前端沒有傳值的情況,如果此時僅僅設置了required=false,會報500錯誤(下圖異常)因為基本數據類型無法接收null,

 

 3.如果后端使用的是引用數據類型,則無需設置required=false和defaultValue

因為即使前端沒有傳入參數值,引用數據類型是可以接收null的

  @RequestMapping(method = RequestMethod.GET,value = "selectStudentById")
    public Student selectStudentById(@RequestParam(value = "id") Integer id){
        return studentService.selectStudentById(id);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM