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

springmvc如何使用POJO作为参数

程序员文章站 2024-02-06 19:40:58
这篇文章主要介绍了springmvc如何使用pojo作为参数,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 springmvc会按...

这篇文章主要介绍了springmvc如何使用pojo作为参数,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

springmvc会按请求参数名和pojo属性名进行匹配,自动为该对象填充属性值,支持级联属性。

user.java

package com.gong.springmvc.entities;

public class user {
  private string username;
  private string password;
  private string email;
  private integer age;
  address address;
  public string getusername() {
    return username;
  }
  public void setusername(string username) {
    this.username = username;
  }
  public string getpassword() {
    return password;
  }
  public void setpassword(string password) {
    this.password = password;
  }
  public string getemail() {
    return email;
  }
  public void setemail(string email) {
    this.email = email;
  }
  public integer getage() {
    return age;
  }
  public void setage(integer age) {
    this.age = age;
  }
  public address getaddress() {
    return address;
  }
  public void setaddress(address address) {
    this.address = address;
  }
  @override
  public string tostring() {
    return "user [username=" + username + ", password=" + password + ", email=" + email + ", age=" + age
        + ", address=" + address + "]";
  }
}

address.java

package com.gong.springmvc.entities;

public class address {
  private string city;
  private string street;
  public string getcity() {
    return city;
  }
  public void setcity(string city) {
    this.city = city;
  }
  public string getstreet() {
    return street;
  }
  public void setstreet(string street) {
    this.street = street;
  }
  @override
  public string tostring() {
    return "address [city=" + city + ", street=" + street + "]";
  }
  
}

springmvctest.java

import com.gong.springmvc.entities.user;

@requestmapping("/springmvc")
@controller
public class springmvctest {
  private static final string success = "success";
  
  @requestmapping(value="/testpojo")
  public string testpojo(user user) {
    system.out.println("testpojo:"+user);
    return success;
  }
}

index.jsp

<form action="springmvc/testpojo" method="post"><br>
    <span>username:</span><input type="text" name="username"><br>
    <span>password:</span><input type="password" name="password"><br>
    <span>email:</span><input type="text" name="password"><br>
    <span>age:</span><input type="text" name="password"><br>
    <span>city:</span><input type="text" name="address.city"><br>
    <span>street:</span><input type="text" name="address.street"><br>
    <input type="submit" value="submit"><br>
  </form>

启动tomcat服务器之后:

springmvc如何使用POJO作为参数

输入相应信息点击提交:

springmvc如何使用POJO作为参数

成功为pojo赋值,包括级联属性address。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。