jaxrs-ri-2.30 не преобразует xml в Pojo во время работы веб-службы REST в Tomcat 9 с Java 12 - PullRequest
1 голос
/ 11 марта 2020

Я использую веб-сервис Rest с реализацией JAX-RS в tomcat 9, установленном локально, с Java 12, установленным в моей системе. Я могу вызвать метод, принимающий запрос POST с полезной нагрузкой JSON. Но не удается вызвать тот же метод с XML полезной нагрузкой.

Нужна помощь для решения этой проблемы.

Ниже приведены подробности моего проекта:

Tomcat version  :   9.0.31 (Installed locally)

Java version    :   12

pom. xml зависимости:

<dependencies>
    <dependency>
        <groupId>org.glassfish.jersey.bundles</groupId>
        <artifactId>jaxrs-ri</artifactId>
        <version>2.30</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

Дескриптор развертывания (web. xml):

  <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>webservices</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>

Customer Pojo (Customer. java):

package domain;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {
    private int id;
    private String firstName;
    private String lastName;
    private String street;
    private String city;
    private String state;
    private String zip;
    private String country;

    @XmlAttribute
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @XmlElement
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @XmlElement
    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @XmlElement
    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    @XmlElement
    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @XmlElement
    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    @XmlElement
    public String getZip() {
        return zip;
    }

    public void setZip(String zip) {
        this.zip = zip;
    }

    @XmlElement
    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @Override
    public String toString() {
        return "Customer{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\''
                + ", street='" + street + '\'' + ", city='" + city + '\'' + ", state='" + state + '\'' + ", zip='" + zip
                + '\'' + ", country='" + country + '\'' + '}';
    }
}

Ресурс (CustomerResource. java):

package webservices;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import domain.Customer;

@Path("/customers")
public class CustomerResource {
    private static Map<Integer, Customer> customerDB = new ConcurrentHashMap<Integer, Customer>();
    private static AtomicInteger idCounter = new AtomicInteger();

    // Constructor
    public CustomerResource() {
    }

    @GET
    @Path("{id}")
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Customer getCustomer(@PathParam("id") int id) {
        final Customer customer = customerDB.get(id);
        if (customer == null) {
            throw new WebApplicationException(Response.Status.NOT_FOUND);
        }
        return customer;
    }

    @GET
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public List<Customer> getCustomer(@QueryParam("start") int start, @QueryParam("size") @DefaultValue("2") int size) {
        List<Customer> custList = new ArrayList<Customer>();
        for (int i = start; i <= size; i++) {
            Customer temp = customerDB.get(i);
            if (temp == null) {
                throw new WebApplicationException(Response.Status.NOT_FOUND);
            } else {
                custList.add(temp);
            }
        }
        return custList;
    }

    @POST
    @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Response createCustomer(Customer customer) {
        customer.setId(idCounter.incrementAndGet());
        customerDB.put(customer.getId(), customer);
        System.out.println("Created customer " + customer.getId());
        return Response.created(URI.create("/customers/" + customer.getId())).build();

    }

    @PUT
    @Path("{id}")
    @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public void updateCustomer(@PathParam("id") int id, Customer customer) {
        Customer current = customerDB.get(id);
        if (current == null)
            throw new WebApplicationException(Response.Status.NOT_FOUND);

        current.setFirstName(customer.getFirstName());
        current.setLastName(customer.getLastName());
        current.setStreet(customer.getStreet());
        current.setCity(customer.getCity());
        current.setState(customer.getState());
        current.setZip(customer.getZip());
        current.setCountry(customer.getCountry());

    }

    @DELETE
    @Path("{id}")
    public void deleteCustomer(@PathParam("id") int id) {
        customerDB.remove(id);
        System.out.println("Deleted !");

    }

}

Детали запроса POST:

Тело запроса:

<customer>
    <firstName>Kundan</firstName>
    <lastName>Verma</lastName>
    <street>M.G.Road</street>
    <city>Mumbai</city>
    <state>Maharashtra</state>
    <zip>713303</zip>
    <country>India</country>
</customer>

Заголовок запроса:

Content-Type    :   application/xml

enter image description here

...