首页 > 代码库 > SpringMVC通过注解获得参数
SpringMVC通过注解获得参数
SpringMVC可以通过RequestParam注解来映射获得参数,具体用法如下:
例子:
配置过程省略
1.新建controller类
1 package com.loger.controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 6 7 @Controller 8 public class RequestParam { 9 10 public static final String SUCCESS = "success"; 11 12 @RequestMapping(value="http://www.mamicode.com/requestparam") 13 public String requestParam(@org.springframework.web.bind.annotation. 14 RequestParam(value="http://www.mamicode.com/username") String un, 15 @org.springframework.web.bind.annotation.RequestParam(value="http://www.mamicode.com/age") Integer age){ 16 17 System.out.println(un + " " + age); 18 19 return SUCCESS; 20 } 21 }
2.index.jsp
运行结果:
补充:如何表单名跟方法的参数名一致的话,无需再用@RequestParam注解来映射。
如改为
@RequestMapping(value="http://www.mamicode.com/requestparam") public String requestParam(String username,Integer age)即可!
用类作为参数,且包含级联属性的参数获取方法:
1.新建Adress类
1 package com.loger.bean; 2 3 public class Address { 4 private String province; 5 private String city; 6 public String getProvince() { 7 return province; 8 } 9 public void setProvince(String province) { 10 this.province = province; 11 } 12 public String getCity() { 13 return city; 14 } 15 public void setCity(String city) { 16 this.city = city; 17 } 18 @Override 19 public String toString() { 20 return "Address [province=" + province + ", city=" + city + "]"; 21 } 22 23 }
2.新建User类
1 package com.loger.bean; 2 3 public class Address { 4 private String province; 5 private String city; 6 public String getProvince() { 7 return province; 8 } 9 public void setProvince(String province) { 10 this.province = province; 11 } 12 public String getCity() { 13 return city; 14 } 15 public void setCity(String city) { 16 this.city = city; 17 } 18 @Override 19 public String toString() { 20 return "Address [province=" + province + ", city=" + city + "]"; 21 } 22 23 }
3.controller
4.表单
User有级联属性Address,表单传入的参数是address.city address.province
1 <form action="pojoparam"> 2 姓名:<input type="text" name="name"><br> 3 年龄:<input type="text" name="age"><br> 4 城市:<input type="text" name="address.city"><br> 5 省份:<input type="text" name="address.province"><br> 6 <input type="submit" value="提交"><br> 7 </form>
运行结果:
SpringMVC通过注解获得参数
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。