简体   繁体   中英

Rest web service to insert data into DB in java

I am trying to insert data in to DB using rest web service in java with postman. My Java code is as below :

Code in CourseService.java :

@POST
    @Path("/createUser")
     @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String createUser(Course course) {

Code in Course.java :

package dto;

public class Course
{
    private int id;
    private String login;


    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public int getId()
    {
        return id;
    }

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

    @Override
    public String toString()
    {
        return "Course [id=" + id + ", name=" + login +"]";
    }

}

I am getting error as below when trying to post the data from postman :

com.sun.jersey.spi.container.ContainerRequest getEntity SEVERE: A message body reader for Java type, class dto.Course, and MIME media type, application/json, was not found

You need to annotate you Course class with @XmlRootElement , as follows, so that jersey can serialize the input json to Course .

Also, make sure that you have jersey-jars in the classpath.

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Course { ... }

@XmlRootElement is an annotation that is commonly used when working with JAXB (JSR-222). It's very purpose is to uniquely associate a root element with a class. JAXB classes map to complex types, it is possible for your class to correspond to multiple root elements.

You may need to annotate your POJO Course Class with

package dto;
import javax.xml.bind.annotation.XmlRootElement

@XmlRootElement(name = "YourPreferredName")
public class Course
{

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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