【发布时间】:2023-03-12 20:50:01
【问题描述】:
我正在尝试学习使用 JAX-RS 实现 RESTful Web 服务。为此,我关注了this tutorial here on YouTube。在本教程中,您可以看到 GET 请求返回一个类的所有私有变量。但是在我的情况下,它没有。当我尝试时,它会返回一个空白屏幕。然后当我将一些成员更改为 public 时,请求只返回那些成员变量。
以下是我的文件:
MovieObject.java
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class MovieObject {
private String movieName;
private String yearOfRelease;
private String movieRating;
public MovieObject(){
}
public MovieObject(String movieName,
String yearOfRelease,
String movieRating){
this.movieName = movieName;
this.yearOfRelease = yearOfRelease;
this.movieRating = movieRating;
}
public String getMovieName(){
return movieName;
}
public String getYearOfRelease(){
return yearOfRelease;
}
public String getMovieRating(){
return movieRating;
}
}
ResourceHandler.java
import java.util.ArrayList;
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("/movies")
public class ResourceHandler {
ListMovies listMovies = new ListMovies();
@GET
@Produces(MediaType.APPLICATION_XML)
public List<MovieObject> getListOfMovies(){
MovieObject mv1 = new MovieObject("The Independence Day 1", "1996", "7");
MovieObject mv2 = new MovieObject("The Independence Day 2", "2016", "4");
List<MovieObject> listOfMovies = new ArrayList<MovieObject>();
listOfMovies.add(mv1);
listOfMovies.add(mv2);
return listOfMovies;
}
}
index.jsp
<html>
<body>
<h2>Jersey RESTful Web Application!</h2>
<p><a href="webapi/myresource">Jersey resource</a>
<p>Visit <a href="http://jersey.java.net">Project Jersey website</a>
for more information on Jersey!
<p> Get list of movies <a href="webapi/movies"> here</a>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>org.auro.self.movielib</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
</web-app>
以下输出是我在 Tomcat 8.0 上运行时得到的结果
如您所见,我只得到了类的 public 成员变量(在本例中为 7 和 4),而不是 private 成员变量。
但在上面的教程中,请求成功返回了所有private 变量。我哪里错了?
【问题讨论】:
-
我在你的代码中看不到任何公共成员变量?