SpringMVC通过注解获得参数的实例

时间:2022-04-21 06:52:44

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

SpringMVC通过注解获得参数的实例

例子:

配置过程省略

1.新建controller类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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

SpringMVC通过注解获得参数的实例

运行结果:

SpringMVC通过注解获得参数的实例

SpringMVC通过注解获得参数的实例

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

如改为

@requestmapping(value="/requestparam")
public string requestparam(string username,integer age)即可!

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

1.新建adress类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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

SpringMVC通过注解获得参数的实例

4.表单

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

?
1
2
3
4
5
6
7
<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>

运行结果:

SpringMVC通过注解获得参数的实例

以上这篇springmvc通过注解获得参数的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/loger1995/p/6274717.html