好的,我的网络服务有问题。
我正在尝试为用户创建一个API,但在我部署应用程序并尝试获取所有用户之后,它给了我一个例外。
这是我的api课程:
package api;
import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import model.UserManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import dto.User;
@Path("/user")
public class UserAPI {
@POST
@Path("create-user/{user}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response saveUser(@PathParam("user") User user) throws JSONException {
UserManager userManager = new UserManager();
userManager.createUser(user);
return Response.status(200).build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public JSONObject getAllUsers() throws JSONException {
JSONObject users = null;
try {
ArrayList<User> usersList = null;
UserManager userManager = new UserManager();
usersList = userManager.getUsers();
JSONObject usersObject = new JSONObject();
for(int i = 0; i < usersList.size(); i++) {
usersObject.put("users", usersList);
}
users = usersObject;
} catch(Exception e) {
e.printStackTrace();
}
return users;
}
@POST
@Path("edit-user/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response editUser(@PathParam("id") int id) throws JSONException {
UserManager userManager = new UserManager();
userManager.editUser(id);
return Response.status(200).build();
}
@POST
@Path("delete-user/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response deleteUser(@PathParam("id") int id) throws JSONException {
UserManager userManager = new UserManager();
userManager.deleteUser(id);
return Response.status(200).build();
}
@POST
@Path("user-login/{user}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response userLogin(@PathParam("user") User user) throws JSONException {
UserManager userManager = new UserManager();
userManager.userLogin(user);
return Response.status(200).build();
}
}
以下是错误日志:
javax.servlet.ServletException: Servlet.init() for servlet Jersey REST Service threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:683)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
com.sun.jersey.spi.inject.Errors$ErrorMessagesException
com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)
com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:790)
com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:491)
com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:321)
com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:376)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:559)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:683)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
答案 0 :(得分:0)
为什么不按原样返回用户列表而不是将其转换为json对象? 试试这个:
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<User> getAllUsers() {
JSONObject users = null;
try {
ArrayList<User> usersList = null;
UserManager userManager = new UserManager();
usersList = userManager.getUsers();
} catch(Exception e) {
e.printStackTrace();
}
return usersList;
}
要从您的视图调用上述方法,您可以使用以下jquery ajax调用:
$.ajax({
type: "GET",
url: "http://localhost:8080/YourProjectName/rest/user",
dataType: "json",
success: function(jsonString) {
alert(jsonString);
},
error: function(xhr) {
alert(JSON.stringify(xhr));
}
});
如果它仍然不起作用,那么它可能是您正在使用的一组库的问题。 因此,我建议您使用GlassFish 4.0应用程序服务器而不是Tomcat服务器。 如果您使用GlassFish服务器,则不得在类路径中包含任何球衣jar,因为GlassFish服务器本身具有所有与球衣相关的jar。
答案 1 :(得分:0)
首先,您要将User对象作为PathParam提交。这不起作用!
另外我想建议你,让UserManager成为单身人士
比,你应该使用GET,PUT,POST,DELETE而不仅仅是GET和POST
我认为例外情况表明你在web.xml中犯了一个错误,并且球衣无法找到(或任何)@Path。因此,请给我们web.xml来证明这一点,并且你也可以通过pom.xml来检查它。
顺便说一句,泽西带来(联合国)marshallers,没有看到使用JSONObject的理由。
这里有些东西:
简单的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- not required with servlet 3.x -->
<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>REST</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>path.to.ResourceConfigOrApplication</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>REST</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
pom.xml(部分)
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.plugin.version>2.5.1</maven.compiler.plugin.version>
<tomcat7.version>2.1</tomcat7.version>
<jersey.version>2.12</jersey.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- JERSEY -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.bundles</groupId>
<artifactId>jaxrs-ri</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-processing</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
// ...
非常简单的用户:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@XmlElement(name="id")
private Integer id;
@XmlElement(name="username")
private String username;
// ...
}
简单的资源(基于你的):
@Path("/users") // changed from user to users
public class UserAPI {
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response saveUser(User user) {
user = UserManager.getInstance().createUser(user);
return Response.ok(user).build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAllUsers() {
List<User> users = UserManager.getInstance().getUsers();
GenericEntity<List<User>> entity = new GenericEntity<List<User>>(
users
){};
return Response.ok( entity ).build();
}
@PUT // edit-user -> PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response editUser(@PathParam("id") Integer id, User user) {
user = UserManager.getInstance().editUser(id, user); // check id and uder.id, if user exists etc
return Response.ok(user).build();
}
@DELETE // delete-user -> DELETE
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteUser(@PathParam("id") Integer id) {
UserManager.getInstance().deleteUser(id);
return Response.ok().build();
}
}