SpringMVC通过注解获得参数

SpringMVC可以通过RequestParam注解来映射获得参数,具体用法如下:

SpringMVC通过注解获得参数

 

 

 

 

例子:

配置过程省略

1.新建controller类

  

SpringMVC通过注解获得参数
 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="/requestparam")
13     public String requestParam(@org.springframework.web.bind.annotation.
14             RequestParam(value="username") String un,
15             @org.springframework.web.bind.annotation.RequestParam(value="age") Integer age){
16         
17         System.out.println(un + " " + age);
18         
19         return SUCCESS;
20     }
21 }
SpringMVC通过注解获得参数

2.index.jsp

SpringMVC通过注解获得参数

运行结果:

SpringMVC通过注解获得参数

SpringMVC通过注解获得参数

 

补充:如果表单名跟方法的参数名一致的话,无需再用@RequestParam注解来映射。

  如改为

   @RequestMapping(value="/requestparam")
     public String requestParam(String username,Integer age)即可!


用类作为参数,且包含级联属性的参数获取方法

  1.新建Adress类
  
SpringMVC通过注解获得参数
 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 }
SpringMVC通过注解获得参数

2.新建User类

SpringMVC通过注解获得参数
 1 package com.loger.bean;
 2 
 3 public class User {
 4     private String name;
 5     private int age;
 6     private Address address;
 7     public String getName() {
 8         return name;
 9     }
10     public void setName(String name) {
11         this.name = name;
12     }
13     public int getAge() {
14         return age;
15     }
16     public void setAge(int age) {
17         this.age = age;
18     }
19     public Address getAddress() {
20         return address;
21     }
22     public void setAddress(Address address) {
23         this.address = address;
24     }
25     @Override
26     public String toString() {
27         return "User [name=" + name + ", age=" + age + ", address=" + address + "]";
28     }
29     
30 }
SpringMVC通过注解获得参数

 

3.controller

SpringMVC通过注解获得参数

4.表单

  User有级联属性Address,表单传入的参数是address.city address.province

SpringMVC通过注解获得参数
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通过注解获得参数

运行结果:

SpringMVC通过注解获得参数