gpt4 book ai didi

java - RESTful JSON 与 Jersey 2.23.2

转载 作者:行者123 更新时间:2023-12-02 10:17:11 28 4
gpt4 key购买 nike

我是 Java、Jersey 和 RESTful 的新手。我最近下载了 Jersey jar 2.23.2 和 Jersey media moxy 2.23.2 以及 java-json 库。

我在谷歌上看到了很多例子,但大多数都不同。没有确切的例子可以遵循。我尝试这样做,但仍然不知道如何使用 http 客户端使用 post 和 get 方法。我发布了下面的代码。

此外,我使用 postman 来测试编码方法,但在 post 方法上出现错误。

SEVERE: Servlet.service() for servlet [Service] in context with path [/com.myexample] threw exception [org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: javax/json/JsonException] with root cause
java.lang.ClassNotFoundException: javax.json.JsonException

这些是库

enter image description here

这是我的 web.xml

    <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>com.myexample</display-name>
<welcome-file-list>
<welcome-file>default.html</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.myexample.resources<param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Service</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
</web-app>

这是我创建的类:

public class Employee {

private String firstName;
private String lastName;

public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}

@Override
public String toString() {
return this.firstName + " " + this.lastName;
}

}

这是 Controller /资源

package com.myexample.resources;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.json.JSONException;
import org.json.JSONObject;

@Path("/test")
public class MyResource {


@GET
@Path("getEmployee")
@Produces(MediaType.APPLICATION_JSON)
public Response getEmployee() throws JSONException{
Employee employee = new Employee();
employee.setFirstName("John");
employee.setLastName("Smith");
JSONObject json = new JSONObject();
json.put("employee", employee);
return Response.status(200).entity(employee).build();
}


@POST
@Path("postEmployee")
@Consumes(MediaType.APPLICATION_JSON)
public Response postEmployee(Employee employee) throws JSONException{
return Response.status(200).entity(employee.toString()).build();
}
}

我尝试创建我的 http 客户端

    public class TestClient {

public static void main(String[] args) {
try {
//POST
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target("http://localhost:8080/com.myexample/api/test/postEmployee");
Employee emp = new Employee();
emp.setFirstName("John");
emp.setLastName("Smith");


Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
//<--As it crashes the following line of this comment, I still don't know how to get my entity
Response response = invocationBuilder.post(Entity.entity(emp, MediaType.APPLICATION_JSON));
//Employee emp = readEntity(Employee.class); //???
} catch (Exception e) {
e.printStackTrace();
}

//GET
try {
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target("http://localhost:8080/com.myexample/api/test/getEmployee");
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
Response response = invocationBuilder.get();
//I get my response but how to deserialize the object
//Employee emp = (Employee)response.getEntity(); //CRASH, cannot cast
} catch (Exception e) {
e.printStackTrace();
}
}

}

因为我仍然不知道如何在客户端上检索对象,但我使用 postman 来测试 Controller 。

这是使用 postman 获取方法的输出。有效

enter image description here

这是 postman 的 post 方法的输出。不起作用

enter image description here

这是一个完整的错误

Aug 18, 2016 11:37:59 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Service] in context with path [/com.myexample] threw exception [org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: javax/json/JsonException] with root cause
java.lang.ClassNotFoundException: javax.json.JsonException
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1313)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1164)
at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.getNewXMLReader(SAXUnmarshaller.java:200)
at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.getXMLReader(SAXUnmarshaller.java:188)
at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:425)
at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:375)
at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:708)
at org.eclipse.persistence.internal.oxm.XMLUnmarshaller.unmarshal(XMLUnmarshaller.java:643)
at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:339)
at org.eclipse.persistence.jaxb.rs.MOXyJsonProvider.readFrom(MOXyJsonProvider.java:660)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:256)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:235)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:155)
at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundReadFrom(MappableExceptionWrapperInterceptor.java:74)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:155)
at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1085)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:874)
at org.glassfish.jersey.server.ContainerRequest.readEntity(ContainerRequest.java:271)
at org.glassfish.jersey.server.internal.inject.EntityParamValueFactoryProvider$EntityValueFactory.provide(EntityParamValueFactoryProvider.java:96)
at org.glassfish.jersey.server.spi.internal.ParamValueFactoryWithSource.provide(ParamValueFactoryWithSource.java:71)
at org.glassfish.jersey.server.spi.internal.ParameterValueHelper.getParameterValues(ParameterValueHelper.java:94)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$AbstractMethodParamInvoker.getParamValues(JavaResourceMethodDispatcherProvider.java:127)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1527)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1484)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)

最佳答案

您需要寻找 jersey-media-mody 的正确依赖项。使用https://jar-download.com/寻找依赖项,尽管从现在开始最好使用 Maven,好吗?

版本号要非常具体。

关于java - RESTful JSON 与 Jersey 2.23.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39030754/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com