SpringMVC - 数据绑定(Xml、@InitBinder、Set、嵌套对象、多个对象)(二)

简介: SpringMVC - 数据绑定(Xml、@InitBinder、Set、嵌套对象、多个对象)(二)

Entity类: 

package com.imooc.object;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="admin")
public class Admin {
    private String name;
    private Integer age;
    @XmlElement(name="name")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @XmlElement(name="age")
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Admin{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
package com.imooc.object;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class User {
    private String name;
    private Integer age;
    private ContactInfo contactInfo;
    public ContactInfo getContactInfo() {
        return contactInfo;
    }
    public void setContactInfo(ContactInfo contactInfo) {
        this.contactInfo = contactInfo;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public static void main(String[] args) {
        Set<User> u = new HashSet<User>();
        User u1 = new User();
        u1.setName("aa");
        User u2 = new User();
        u2.setName("aa");
        u.add(u1);
        u.add(u2);
        System.out.println("size:"+u.size());
        System.out.println(u);
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return Objects.equals(name, user.name) &&
                Objects.equals(age, user.age);
    }
    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
    //    @Override
//    public String toString() {
//        return "User{" +
//                "name='" + name + '\'' +
//                ", age=" + age +
//                '}'+this.hashCode();
//    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", contactInfo=" + contactInfo +
                '}';
    }
}
package com.imooc.object;
public class ContactInfo {
    private String phone;
    private String address;
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "ContactInfo{" +
                "phone='" + phone + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}
package com.imooc.object;
import java.util.LinkedHashSet;
import java.util.Set;
public class UserSetForm {
    private Set<User> users;
    private UserSetForm(){
        users = new LinkedHashSet<User>();
        users.add(new User());
        users.add(new User());
    }
    public Set<User> getUsers() {
        return users;
    }
    public void setUsers(Set<User> users) {
        this.users = users;
    }
    @Override
    public String toString() {
        return "UserSetForm{" +
                "users=" + users +
                '}';
    }
}
package com.imooc.object;
import java.util.List;
public class UserListForm {
    private List<User> users;
    public List<User> getUsers() {
        return users;
    }
    public void setUsers(List<User> users) {
        this.users = users;
    }
    @Override
    public String toString() {
        return "UserListForm{" +
                "users=" + users +
                '}';
    }
}
package com.imooc.object;
import java.util.Map;
public class UserMapForm {
    private Map<String,User> users;
    @Override
    public String toString() {
        return "UserMapForm{" +
                "users=" + users +
                '}';
    }
    public Map<String, User> getUsers() {
        return users;
    }
    public void setUsers(Map<String, User> users) {
        this.users = users;
    }
}

Web类:

package com.imooc.controller;
import com.imooc.object.*;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
@Controller
public class TestController {
    //todo     http://localhost:8080/baseType.do?age=10
    //todo 500 http://localhost:8080/baseType.do
    //todo 400 http://localhost:8080/baseType.do?age=abc
    @RequestMapping(value = "baseType.do")
    @ResponseBody
    public String baseType(int age){
        return "age:"+age;
    }
    //todo     http://localhost:8080/baseType2.do?age=10
    //todo     http://localhost:8080/baseType2.do
    //todo 400 http://localhost:8080/baseType2.do?age=abc
    @RequestMapping(value = "baseType2.do")
    @ResponseBody
    public String baseType2(Integer age){
        return "age:"+age;
    }
    //todo http://localhost:8080/array.do?name=Tom&name=Lucy&name=Jim
    @RequestMapping(value = "array.do")
    @ResponseBody
    public String array(String[] name){
        StringBuilder sbf = new StringBuilder();
        for(String item : name){
            sbf.append(item).append(" ");
        }
        return sbf.toString();
    }
    //todo http://localhost:8080/object.do?name=Tom&age=10
    //TODO http://localhost:8080/object.do?name=Tom&age=10&contactInfo.phone=10086
    //TODO http://localhost:8080/object.do?user.name=Tom&admin.name=Lucy&age=10
    @RequestMapping(value = "object.do")
    @ResponseBody
    public String object(User user,Admin admin){
        return user.toString()+" "+admin.toString();
    }
    @InitBinder("user")
    public void initUser(WebDataBinder binder){
        binder.setFieldDefaultPrefix("user.");
    }
    @InitBinder("admin")
    public void initAdmin(WebDataBinder binder){
        binder.setFieldDefaultPrefix("admin.");
    }
    //TODO http://localhost:8080/list.do?users[0].name=Tom&users[1].name=Lucy
    //TODO http://localhost:8080/list.do?users[0].name=Tom&users[1].name=Lucy&users[20].name=Jim
    @RequestMapping(value = "list.do")
    @ResponseBody
    public String list(UserListForm userListForm){
        return "listSize:"+userListForm.getUsers().size() + "  " + userListForm.toString();
    }
    //TODO http://localhost:8080/set.do?users[0].name=Tom&users[20].name=Lucy
    @RequestMapping(value = "set.do")
    @ResponseBody
    public String set(UserSetForm userSetForm){
        return userSetForm.toString();
    }
    //TODO http://localhost:8080/map.do?users['X'].name=Tom&users['X'].age=10&users['Y'].name=Lucy
    @RequestMapping(value = "map.do")
    @ResponseBody
    public String map(UserMapForm userMapForm){
        return userMapForm.toString();
    }
//    {
//        "name": "Jim",
//            "age": 16,
//            "contactInfo": {
//                "address": "beijing",
//                "phone": "10010"
//              }
//    }
    //application/json
    @RequestMapping(value = "json.do")
    @ResponseBody
    public String json(@RequestBody User user){
        return user.toString();
    }
//    <?xml version="1.0" encoding="UTF-8" ?>
//    <admin>
//      <name>Jim</name>
//      <age>16</age>
//    </admin>
    //application/xml
    @RequestMapping(value = "xml.do")
    @ResponseBody
    public String xml(@RequestBody Admin admin){
        return admin.toString();
    }

附:


如果没有@InitBinder注解的辅助方法,根据之前所学的理论,这个方法如果传递user.name,admin.name结果会怎么样呢?

答:user和admin的name属性都为null。

Set集合报错表面取决于提前添加了对应个数的对象,但是底层取决于hashCode方法的判断依据。所以一般情况不建议使用Set来做集合,用List。

待更新...


目录
相关文章
|
7月前
|
存储 JavaScript 索引
js开发:请解释什么是ES6的Map和Set,以及它们与普通对象和数组的区别。
ES6引入了Map和Set数据结构。Map的键可以是任意类型且有序,与对象的字符串或符号键不同;Set存储唯一值,无重复。两者皆可迭代,支持for...of循环。Map有get、set、has、delete等方法,Set有add、delete、has方法。示例展示了Map和Set的基本操作。
106 3
|
4月前
|
XML 缓存 API
【Azure API 管理】使用APIM进行XML内容读取时遇见的诡异错误 Expression evaluation failed. Object reference not set to an instance of an object.
【Azure API 管理】使用APIM进行XML内容读取时遇见的诡异错误 Expression evaluation failed. Object reference not set to an instance of an object.
|
4月前
|
XML 自然语言处理 Java
Java 中的 XML 数据绑定
【8月更文挑战第22天】
33 0
|
6月前
|
XML Java 数据格式
Java一分钟之-JAXB:Java对象到XML绑定
【6月更文挑战第1天】Java Architecture for XML Binding (JAXB) 是Java平台标准,用于自动转换Java对象和XML。它通过注解实现声明式映射,简化XML处理。本文介绍了JAXB的基本使用、常见问题和最佳实践,包括对象到XML(Marshalling)和XML到对象(Unmarshalling)过程,并通过示例展示如何在Java类和XML之间进行转换。注意类型匹配、注解冲突和JAXB上下文创建等问题,以及如何优化性能和避免循环引用。
401 3
|
6月前
|
XML Java 数据格式
SpringMVC的XML配置解析-spring18
SpringMVC的XML配置解析-spring18
|
7月前
SpringMVC 域对象共享数据
SpringMVC 域对象共享数据
33 0
|
7月前
|
XML 数据格式
com.sun.istack.SAXException2: 在对象图中检测到循环。这将产生无限深的 XML
com.sun.istack.SAXException2: 在对象图中检测到循环。这将产生无限深的 XML
|
7月前
【SpringMVC】SpringMVC方式,向作用域对象共享数据(ModelAndView、Model、map、ModelMap)
【SpringMVC】SpringMVC方式,向作用域对象共享数据(ModelAndView、Model、map、ModelMap)
77 1
|
7月前
|
SQL Java 关系型数据库
Hibernate - 对象关系映射文件(*.hbm.xml)详解
Hibernate - 对象关系映射文件(*.hbm.xml)详解
308 1
|
7月前
|
XML JavaScript Java
Spring5源码(16)-Spring将Xml文件解析为Document对象
Spring5源码(16)-Spring将Xml文件解析为Document对象
69 0