简体   繁体   中英

How to get Bean object when Json is sent to a HTTP POST method of RestFul web service?

I have created a simple Restful web service to store the JSON object sent from Restful webservice client into PostgreSQL database using hibernate.

Below is the MyResource class which handles all the HTTP requests comes to the web service.

@Path("titles")
public class MyResource {

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String addTitle(MessengerBean msgBean){
    System.out.println("in add title" + msgBean.getCountry());
    MessageDAO dao = new MessageDAO();
    boolean result = dao.addNewTitle(msgBean);
    if(result==true){
        return "Title Added";
    }
    else{
        return "Failed to Add";
    }
}
}

Below is my DAO class

public class MessageDAO {

public Session getConnection() 
{
    Configuration cfg=new Configuration();
    cfg.configure("/hibernate.cfg.xml");
    SessionFactory sf=cfg.buildSessionFactory();
    Session session=sf.openSession();
    return session;
}

private void closeConnection(Session s) {
    s.close();
}

public boolean addNewTitle(MessengerBean msgBean) {
    System.out.println("in addNewTitle" + msgBean.getCountry());
    MessageDAO dao = new MessageDAO();
    /* Getting Session Object */
    Session session = dao.getConnection();
    Transaction t = session.beginTransaction();
    session.save(msgBean);
    dao.closeConnection(session);
    return true;
}
}

Below is my Bean class

@XmlRootElement
@Entity
@Table(name = "TABLE_TITLES", schema="movieflixtitles")
public class MessengerBean implements Serializable{
private String Title;
private int Year;
private String Rated;
private Date Released;
private int Runtime;
private String Genre;
private String Director;
private String Writer;
private String Actors;
private String Plot;
private String Language;
private String Country;
private String Awards;
private String Poster;
private String Metascore;
private float imdbRating;
private String imdbVotes;

@Id
private String imdbID;
private String Type;
public String getTitle() {
    return Title;
}
public void setTitle(String title) {
    Title = title;
}
public int getYear() {
    return Year;
}
public void setYear(int year) {
    Year = year;
}
public String getRated() {
    return Rated;
}
public void setRated(String rated) {
    Rated = rated;
}
public Date getReleased() {
    return Released;
}
public void setReleased(Date released) {
    Released = released;
}
public int getRuntime() {
    return Runtime;
}
public void setRuntime(int runtime) {
    Runtime = runtime;
}
public String getGenre() {
    return Genre;
}
public void setGenre(String genre) {
    Genre = genre;
}
public String getDirector() {
    return Director;
}
public void setDirector(String director) {
    Director = director;
}
public String getWriter() {
    return Writer;
}
public void setWriter(String writer) {
    Writer = writer;
}
public String getActors() {
    return Actors;
}
public void setActors(String actors) {
    Actors = actors;
}
public String getPlot() {
    return Plot;
}
public void setPlot(String plot) {
    Plot = plot;
}
public String getLanguage() {
    return Language;
}
public void setLanguage(String language) {
    Language = language;
}
public String getCountry() {
    return Country;
}
public void setCountry(String country) {
    Country = country;
}
public String getAwards() {
    return Awards;
}
public void setAwards(String awards) {
    Awards = awards;
}
public String getPoster() {
    return Poster;
}
public void setPoster(String poster) {
    Poster = poster;
}
public String getMetascore() {
    return Metascore;
}
public void setMetascore(String metascore) {
    Metascore = metascore;
}
public float getImdbRating() {
    return imdbRating;
}
public void setImdbRating(float imdbRating) {
    this.imdbRating = imdbRating;
}
public String getImdbVotes() {
    return imdbVotes;
}
public void setImdbVotes(String imdbVotes) {
    this.imdbVotes = imdbVotes;
}
public String getImdbID() {
    return imdbID;
}
public void setImdbID(String imdbID) {
    this.imdbID = imdbID;
}
public String getType() {
    return Type;
}
public void setType(String type) {
    Type = type;
}

}

Below is my hibernate configuration file

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
      "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
      "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

 <!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
    <property name="hbm2ddl.auto">update</property>
    <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <property name="connection.url">jdbc:postgresql://localhost:5555/movieflix</property>
    <property name="connection.username">postgres</property>
    <property name="connection.password">password</property>
    <property name="connection.driver_class">org.postgresql.Driver</property>
    <mapping class="com.web.messenger.model.MessengerBean"/>
</session-factory>

</hibernate-configuration>

JSON object passed through POST MASTER plugin and the Content-Type, Accept values are set to "application/json" in this restful webservice plugin to check the output.

{
"Title": "Avengers: Age of Ultron",
"Year": "2015",
"Rated": "PG-13",
"Released": "01 May 2015",
"Runtime": "141 min",
"Genre": "Action, Adventure, Sci-Fi",
"Director": "Joss Whedon",
"Writer": "Joss Whedon, Stan Lee (Marvel comics), Jack Kirby (Marvel comics)",
"Actors": "Robert Downey Jr., Chris Hemsworth, Mark Ruffalo, Chris Evans",
"Plot": "When Tony Stark and Bruce Banner try to jump-start a dormant peacekeeping program called Ultron, things go horribly wrong and it's up to Earth's Mightiest Heroes to stop the villainous Ultron from enacting his terrible plans.",
"Language": "English",
"Country": "USA",
"Awards": "1 win & 12 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTU4MDU3NDQ5Ml5BMl5BanBnXkFtZTgwOTU5MDUxNTE@._V1_SX300.jpg",
"Metascore": "66",
"imdbRating": "7.6",
"imdbVotes": "370,909",
"imdbID": "tt2395427",
"Type": "movie"
 }

The above code is creating table "TABLE_TITLES" in my database schema but null values are getting stored. Even the "System.out.println("in add title" + msgBean.getCountry());" statement inside MyResouce class is printing null values. The return value ("Title Added") is getting returned in the message body of POST MASTER after storing the null object in the database.

There is no such thing as ContextType for Http Header.

Use ContentType: application/json This should ideally fix your issue.

I believe you have not added json support in your project. You need to have json support jars in your class path (in case it is a maven project, you can easily add them as dependencies in your project's pom.xml) for json serialization and deserialization.

For reference, take a look at this example json-example-with-jersey . For documentation, take a look at this: jersey-json

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