首页 > 代码库 > 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通过注解获得参数