简体   繁体   English

使用Jersey 2.23.2的RESTful JSON

[英]RESTful JSON with Jersey 2.23.2

I'm new to Java, Jersey and RESTful. 我是Java,Jersey和RESTful的新手。 I recently downloaded the Jersey jar 2.23.2 and the Jersey media moxy 2.23.2 and the java-json library. 我最近下载了Jersey jar 2.23.2和Jersey media moxy 2.23.2以及java-json库。

I'm see many examples in google but mostly all of them differ. 我在谷歌看到很多例子,但大多数都不同。 There is no an exact example to follow. 没有一个确切的例子可以遵循。 I tried to do it, but still don't know how to consume the post and get methods with http client. 我试图这样做,但仍然不知道如何使用http客户端消费帖子和获取方法。 I posted the code below. 我发布了以下代码。

Also, I used the postman to test the coded methods but I get an error on the post method. 此外,我使用邮差测试编码方法,但我在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

These are the libraries 这些是图书馆

在此输入图像描述

This is my web.xml 这是我的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>

This is the class that I created: 这是我创建的类:

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

}

This is the controller/resource 这是控制器/资源

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

I tried to create my http client 我试着创建我的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();
            }
        }

}

As I still don't know how to retrieve the object on my client, but I used postman to test the controller. 因为我仍然不知道如何在我的客户端上检索对象,但我使用邮递员来测试控制器。

This is the output from get method with postman. 这是带邮递员的get方法的输出。 It works 有用

在此输入图像描述

This is the output from post method with postman. 这是邮递员post方法的输出。 It doesn't work 它不起作用

在此输入图像描述

This is full error 这是完整的错误

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)

You need to hunt down the jersey-media-mody's correct dependencies. 你需要追捕jersey-media-mody的正确依赖关系。 Use https://jar-download.com/ to hunt down dependencies although it's best to use Maven is best from now on okay? 使用https://jar-download.com/来追捕依赖关系,尽管从现在起最好使用Maven是好的吗?

Be very specific with the version numbers. 对版本号非常具体。

From the Documentation , 文档中

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found. 搜索的类定义在编译当前正在执行的类时存在,但无法再找到该定义。

So, when you built your war, the missing dependency didn't get packaged with it. 因此,当你构建你的战争时,缺少的依赖关系没有打包它。

The better option for you to start will be with Maven. 你可以选择Maven来开始更好的选择。 Create a maven project from an archetype. 从原型创建maven项目。

Here is a very simple guide on how to build rest apis, REST API EXAMPLE 这是一个关于如何构建rest apis的简单指南, REST API示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM