springmvc的@RequestMapping、@PathVariable、@RequestParam

來源:互聯網
上載者:User
springmvc@RequestMapping@PathVariable@RequestParam springmvc的@RequestMapping、@PathVariable、@RequestParam @RequestMapping("/somepath/{userName}") public String register(@PathVariable(value = "userName") String userName) { ModelAndView mav = new ModelAndView(); return "user/createSuccess"; } 在springmvc註解的@RequestMapping("/somepath/{userName}")如何處理預設值的情況,比如我在發送請求的時候,userName有時候是沒有的,所以導到了不能匹配這個action http://localhost:8080/spc/movie/somepath/就不能匹配上面的請求: http://localhost:8080/spc/movie/somepath/tom而這個才可以匹配。 @PathVariable 會將url中的參數解析到對應的方法參數上,需要在@RequestMapping()指定匹配模式 @RequestMapping("somepath/{userName}") 這時你訪問地址"somepath/Tom"就能把"Tom"解析到方法參數userName上 @RequestParam用於將請求參數區資料對應到功能處理方法的參數上 public String requestparam2(@RequestParam("username") String username) 請求中包含username參數(如/requestparam1?username=zhang),則自動傳入。 接下來我們看一下@RequestParam註解主要有哪些參數: value:參數名字,即入參的請求參數名字,如username表示請求的參數區中的名字為username的參數的值將傳入; required:是否必須,預設是true,表示請求中一定要有相應的參數,否則將報404錯誤碼; defaultValue:預設值,表示如果請求中沒有同名參數時的預設值,預設值可以是SpEL運算式,如“#{systemProperties['java.vm.version']}”。 public String requestparam4(@RequestParam(value="username",required=false) String username) 表示請求中可以沒有名字為username的參數,如果沒有預設為null,此處需要注意如下幾點: 原子類型:必須有值,否則拋出異常,如果允許空值請使用封裝類代替。 Boolean封裝類型類型:預設Boolean.FALSE,其他參考型別預設為null。 public String requestparam5(@RequestParam(value="username", required=true, defaultValue="zhang") String username) 表示如果請求中沒有名字為username的參數,預設值為“zhang”。 如果請求中有多個同名的應該如何接收呢。如給使用者授權時,可能授予多個許可權,首先看下如下代碼: public String requestparam7(@RequestParam(value="role") String roleList)如果請求參數類似於url?role=admin&rule=user,則實際roleList參數入參的資料為“admin,user”,即多個資料之間使用“,”分割;我們應該使用如下方式來接收多個請求參數: public String requestparam7(@RequestParam(value="role") String[] roleList) 或 public String requestparam8(@RequestParam(value="list") List list)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.