简体   繁体   English

Spring MVC:RequestBody + ResponseEntity:如何在没有某些obj字段的情况下返回对象/实体

[英]Spring MVC: RequestBody + ResponseEntity: How to return an object/entity without some of the obj fields

I want to see is there a better way to achieve this: currently, I have a User class, UserRequest class and UserResponse class, they are all very similar or subset of User. 我想看看有没有更好的方法可以实现此目的:目前,我有一个User类,UserRequest类和UserResponse类,它们都非常相似或是User的子集。

class User{
 long id;
 String name;
 String password;
 String field1;
 String[] array1;
}

class UserRequest{
 String name;
 String password;
}

class UserResponse{
 long id;
 String name;
 String field1;
}

So instead of having 3 similar classes, can I limit the fields using User class for the ResponseEntity? 因此,除了可以使用3个类似的类之外,我还可以将User类用于ResponseEntity来限制字段吗? or what would be a better way to achieve what i am trying to do without having all the similar classes? 还是在没有所有类似课程的情况下实现我正在尝试的更好的方法是什么?

 public @ResponseBody ResponseEntity<UserResponse> login(@RequestBody @Valid UserRequest request) {

  User user = userRep.findByPrimaryEmailLike(request.getPrimaryEmail());
  return new ResponseEntity<UserResponse>(user.getSuccessLoginResponse(), HttpHeaderUtils.getHeader4Json(), HttpStatus.OK);

 }

Depends on what your format and (de-)serialization handler is, but making the wild guess it's JSON via Jackson: 取决于您的格式和(反)序列化处理程序是什么,但是通过Jackson可以大胆地猜测它是JSON:

import org.codehaus.jackson.annotate.JsonIgnore;
class User {

    long id;
    String name;
    String password;
    String field1;
    String[] array1;

    @JsonIgnore
    public String[] getArray1() {
        return array1;
    }

    @JsonIgnore
    public void setArray1(String[] array1) {
        this.array1 = array1;
    }

    public String getField1() {
        return field1;
    }

    @JsonIgnore
    public void setField1(String field1) {
        this.field1 = field1;
    }

    public long getId() {
        return id;
    }

    @JsonIgnore
    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @JsonIgnore
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

If you use a SpringMVC extension like Yoga , you can return only the User object, but customize the request to determine which fields are returned in the @ResponseBody. 如果使用延长用SpringMVC像瑜伽 ,你只能返回用户对象,但定制确定哪些字段在被@ResponseBody返回的请求。 For example, 例如,

GET http://mydomain.com/user?selector=name,password

GET http://mydomain.com/user?selector=id,name,field1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM