您好,登錄后才能下訂單哦!
SpringMVC中的參數怎么利用注解獲取?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
SpringMVC可以通過RequestParam注解來映射獲得參數,具體用法如下:
例子:
配置過程省略
1.新建controller類
package com.loger.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class RequestParam { public static final String SUCCESS = "success"; @RequestMapping(value="/requestparam") public String requestParam(@org.springframework.web.bind.annotation. RequestParam(value="username") String un, @org.springframework.web.bind.annotation.RequestParam(value="age") Integer age){ System.out.println(un + " " + age); return SUCCESS; } }
2.index.jsp
運行結果:
補充:如果表單名跟方法的參數名一致的話,無需再用@RequestParam注解來映射。
如改為
@RequestMapping(value="/requestparam")
public String requestParam(String username,Integer age)即可!
用類作為參數,且包含級聯屬性的參數獲取方法:
1.新建Adress類
package com.loger.bean; public class Address { private String province; private String city; public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public String toString() { return "Address [province=" + province + ", city=" + city + "]"; } }
2.新建User類
package com.loger.bean; public class User { private String name; private int age; private Address address; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } @Override public String toString() { return "User [name=" + name + ", age=" + age + ", address=" + address + "]"; } }
3.controller
4.表單
User有級聯屬性Address,表單傳入的參數是address.city address.province
<form action="pojoparam"> 姓名:<input type="text" name="name"><br> 年齡:<input type="text" name="age"><br> 城市:<input type="text" name="address.city"><br> 省份:<input type="text" name="address.province"><br> <input type="submit" value="提交"><br> </form>
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。