long pham
long pham

Reputation: 37

return type xml or json in restful

I have some code below, and when I test it with postman. It occurs an error "500". I don't understand the advantage of "@Produces(MediaType.APPLICATION_XML)". Does it define return type automatically as XML, or not.

import java.sql.SQLException;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/UserService")
public class UserService {
    UserDAO userDAO = new UserDAO();

    @GET
    @Path("/users")
    @Produces(MediaType.APPLICATION_XML)
    public List<User> getUsers() throws ClassNotFoundException, SQLException {
        return userDAO.getAllUsers();
    }

}

Upvotes: 1

Views: 509

Answers (4)

M. Deinum
M. Deinum

Reputation: 124431

It specifies the content-types (yes plural!) that this method produces (hence the name). This is used to

  1. select the correct method to execute for an incoming request
  2. determine what to produce as a response.

In your case when an incoming request needs JSON you will get a HTTP 406 as there is nothing that can handle this method.

Now if the method would have been annotated with @Produces( {MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON} ) it would be served and JSON would have been produced. Now you have single method serving both JSON and XML. What to serve is determined based on the Accept-Header of the incoming request.

Upvotes: 1

Ashish Shetkar
Ashish Shetkar

Reputation: 1467

//To process HTTP GET requests.
 @GET

//@Path Identifies the URI path that a resource class will serve requests for.
 @Path("/abcd")

//@Produces defines the media type(s) that the methods of a resource class can produce.
@Produces(MediaType.APPLICATION_XML

I hope you have prepared the User class - with XmlRootElement and XML elements

for an example -

@XmlRootElement(name="User")
public class User{

    private int id;
    private String name; 

    public User() {

    }


    @XmlElement
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    @XmlElement
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }  
}

Upvotes: 2

veben
veben

Reputation: 22262

Yes, @Produce define the produced format. So your list of users will be format as XML. Don't forget to parametrize Postman header to accept XML.

Upvotes: 0

WGSSAMINTHA
WGSSAMINTHA

Reputation: 190

As your method, result return in xml format.

Upvotes: 0

Related Questions