Reputation: 37
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
Reputation: 124431
It specifies the content-types (yes plural!) that this method produces (hence the name). This is used to
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
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
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