欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

springmvc如何使用POJO作为参数

时间:2023-01-18 11:01:14|栏目:JAVA代码|点击:

这篇文章主要介绍了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服务器之后:

输入相应信息点击提交:

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

上一篇:Java之IO流面试题案例讲解

栏    目:JAVA代码

下一篇:Java 深入浅出讲解代理模式

本文标题:springmvc如何使用POJO作为参数

本文地址:http://www.codeinn.net/misctech/223939.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有