欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-23 18:01:46
springmvc可以通过requestparam注解来映射获得参数,具体用法如下: 例子: 配置过程省略 1.新建controller类 packag...

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

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

例子:

配置过程省略

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

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

运行结果:

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

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

补充:如果表单名跟方法的参数名一致的话,无需再用@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

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

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>

运行结果:

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

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