我在下面以及与邮递员一起测试时有一些代码。发生错误“ 500”。我不了解“ @Produces(MediaType.APPLICATION_XML)”的优点。是否自动将返回类型定义为XML。

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();
    }

}

最佳答案

//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


我希望您已经准备了User类-具有XmlRootElement和XML元素

举个例子-

@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;
    }
}

关于java - 静态返回类型xml或json,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53409911/

10-10 13:54