简体   繁体   中英

RESTful JSON with Jersey 2.23.2

I'm new to Java, Jersey and RESTful. I recently downloaded the Jersey jar 2.23.2 and the Jersey media moxy 2.23.2 and the java-json library.

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. I posted the code below.

Also, I used the postman to test the coded methods but I get an error on the post method.

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

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

    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. It works

在此输入图像描述

This is the output from post method with postman. 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. Use https://jar-download.com/ to hunt down dependencies although it's best to use Maven is best from now on okay?

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. Create a maven project from an archetype.

Here is a very simple guide on how to build rest apis, REST API EXAMPLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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