【问题标题】:How to save user by using form-data in spring boot rest & postman?如何在 Spring Boot Rest & Postman 中使用表单数据来保存用户?
【发布时间】:2019-09-14 10:59:26
【问题描述】:

我正在开发一个用于登录和注册的 Spring Boot Rest API。通过使用邮递员正文中的@RequestBody 作为原始数据,我能够将数据保存在数据库中。但我想从每个字段的邮递员那里发送表单数据。在这种情况下,我应该在控制器中使用哪个注释。

如果有人有一个简单的例子,那就太好了!

请检查图片:

道类-

@Repository
public class CustomerDaoImpl implements CustomerDao {

@Autowired
private SessionFactory sessionFactory;

@Override
public List<Customer> getCustomers() {

    Session session = sessionFactory.getCurrentSession(); 

    Query<Customer> query = session.createQuery("from Customer", 
                                                Customer.class);

    List<Customer> customers = query.getResultList();

    return customers;
}

@Override
public Customer getCustomer(int id) {

    Session session = sessionFactory.getCurrentSession(); 

    Customer customer = session.get(Customer.class, id);

    return customer;
}

@Override
public void saveCustomer(Customer theCustomer) {

    Session session = sessionFactory.getCurrentSession();

    session.saveOrUpdate(theCustomer);

}

@Override
public void deleteCustomer(int Id) {

    Session session = sessionFactory.getCurrentSession();

    Query query = session.createQuery("Delete from Customer where id=:customerId");

    query.setParameter("customerId", Id);

    query.executeUpdate();
}

@Override
public Customer getCustomer(String emailId, String password) {
    Customer customer = null;
    Session session = sessionFactory.getCurrentSession();
    Query<Customer> query = session.createQuery("from Customer where emailId=:emailId and "
            + " password=:password");

    query.setParameter("emailId", emailId);
    query.setParameter("password", password);

    List<Customer> list = query.getResultList();

    try {
        return customer = list.get(0);
    }
    catch(Exception e) {
        e.getMessage();
        return null;
    }
 }

}

POJO 类 -

import java.sql.Timestamp;



@Entity
@Table(name="tbl_user_register")
@JsonInclude(Include.NON_EMPTY) 
@JsonIgnoreProperties(ignoreUnknown = true)

public class Customer {

@Id
@Column(name="user_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;

@Column(name="name")
private String name;

@Column(name="email_id")
private String emailId;

@Column(name="mobile")
private String mobile;

@Column(name="business_name")
private String businessName;

@Column(name="address")
private String address;

@Column(name="password")
private String password;

@Column(name="created")
@CreationTimestamp
private Timestamp created;

@Column(name="user_type")
private int userType;

@Column(name="parent_type")
private int parentType;

public Customer() {
    super();
}

public Customer(String name, String emailId, String mobile, String businessName, String address, String password,
        Timestamp created, int userType, int parentType) {
    super();
    this.name = name;
    this.emailId = emailId;
    this.mobile = mobile;
    this.businessName = businessName;
    this.address = address;
    this.password = password;
    this.created = created;
    this.userType = userType;
    this.parentType = parentType;
}



public Customer(int id, String name, String emailId, String mobile, String businessName, String address,
        String password, Timestamp created, int userType, int parentType) {
    super();
    this.id = id;
    this.name = name;
    this.emailId = emailId;
    this.mobile = mobile;
    this.businessName = businessName;
    this.address = address;
    this.password = password;
    this.created = created;
    this.userType = userType;
    this.parentType = parentType;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

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

public String getEmailId() {
    return emailId;
}

public void setEmailId(String emailId) {
    this.emailId = emailId;
}

public String getMobile() {
    return mobile;
}

public void setMobile(String mobile) {
    this.mobile = mobile;
}

public String getBusinessName() {
    return businessName;
}

public void setBusinessName(String businessName) {
    this.businessName = businessName;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public String getPassword() {
    return password;
}

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

public Timestamp getCreated() {
    return created;
}

public void setCreated(Timestamp created) {
    this.created = created;
}

public int getUserType() {
    return userType;
}

public void setUserType(int userType) {
    this.userType = userType;
}

public int getParentType() {
    return parentType;
}

public void setParentType(int parentType) {
    this.parentType = parentType;
}

@Override
public String toString() {
    return "Customer [id=" + id + ", name=" + name + ", emailId=" + emailId + ", mobile=" + mobile
            + ", businessName=" + businessName + ", address=" + address + ", password=" + password + ", created="
            + created + ", userType=" + userType + ", parentType=" + parentType + "]";
 }

}

控制器 -

@RestController
@RequestMapping("/api")
public class CustomerController {

@Autowired
CustomerService customerService;
ResponseHandler response;   

@GetMapping("/customers")
public ResponseEntity<List<Customer>> getCustomers(){

    List<Customer> list = customerService.getCustomers();
    return new ResponseEntity<List<Customer>>(list, HttpStatus.OK);
}


@PostMapping(value="/login")
public Customer getCustomer(@RequestParam(value="emailId") String emailId, @RequestParam(value="password") String password) {


    Customer theCustomer = customerService.getCustomer(emailId, password);

    if(theCustomer == null) {
        throw new CustomerNotFoundException("Customer not found - "+emailId);
    }
    return theCustomer;
}



@PostMapping(value = "/customers", consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
public Customer saveCustomer(@ModelAttribute Customer customer) {

    customerService.saveCustomer(customer);
    return customer;
    }

}

这就是我得到的 - https://imgur.com/RnMkztk

【问题讨论】:

    标签: java json spring rest postman


    【解决方案1】:

    在控制器中,您可以getParameterMap() 为您提供所有表单数据。

    Map<String, String[]> parameterMap = request.getParameterMap();
    

    或者只是将地图作为参数

    @RequestMapping("/yourmapping")
    void method(@RequestParam HashMap<String, Object> formData){
       //rest your code
    }
    

    【讨论】:

    • 好的,所以我将使用 Map 从邮递员表单数据中获取所有字段值,但我仍然需要将其保存到数据库中。因为我正在传递用户 bean 来保存 dao 类的方法。
    • 您可以从地图中获取并将其设置为用户 bean,然后将用户 bean 传递给 dao。
    • 你能给我看一些代码吗?我对此有点陌生。
    • 另外,我在一个字段中发送了创建时间,我该怎么做?
    • 能否请您详细示例,我仍然找不到解决方案
    【解决方案2】:

    您可以在@PostMapping 中提供consumes = MediaType.MULTIPART_FORM_DATA_VALUEDataRequest 是模型,它将包括名称、电子邮件等数据字段。并且还在 DataRequest 中添加 getter setter。

    @PostMapping(value = "/readFile",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String readFile (@ModelAttribute DataRequest dataRequest)  {
        //DataRequest is the POJO in which you can mention the fields you want in the request
        return "done";      
    }
    
    @JsonInclude(Include.NON_EMPTY)
    @JsonIgnoreProperties(ignoreUnknown = true)
    public class DataRequest {
    
        private String _id;
        private Date createTime;
    
        //add getter setters
    
    }
    

    【讨论】:

    • 在一个字段中我发送了创建时间,我该怎么做?
    • 将 createdTime 作为纪元时间发送,在 pojo 模型中将其作为日期发送,用于将时间戳转换为纪元时间,您可以使用:epochconverter.com
    • 你是否在 pojo 类中包含了 getter setter?
    • 我已经包含了它,但现在它显示“不支持内容类型'application/json'”,
    • 您是否在标头中添加了 application/json?如果存在,则将其删除
    猜你喜欢
    • 2017-03-29
    • 1970-01-01
    • 2019-05-17
    • 2015-12-09
    • 1970-01-01
    • 2022-12-15
    • 2019-01-14
    • 1970-01-01
    • 2018-01-13
    相关资源
    最近更新 更多