如何将Java对象从客户端传递到Webservice

时间:2019-07-16 16:15:47

标签: java xml soap jaxb jax-ws

您好,我是Web服务的新手,我试图将Java对象传递给我创建的Web服务,在该Web服务中它具有采用Java对象的Web方法。我在下面附上我的代码。

Web服务类:

@WebService
public class WsTicketService {

    WsTicketStore ticketstore =  new WsTicketStore();

    @WebMethod
    public void createTicket(Ticket ticket) {
        System.out.println("Requested to store a new ticket");
        Ticket myTicket = ticketstore.storeNewTicket(ticket.getReporter(), ticket.getTopic(),ticket.getDescription(), ticket.getType(), ticket.getPriority());
        System.out.println("Ticket Stored");
    }
}

创建票证的客户端类我想将此票证发送到上述Web服务,但是在service.createTicket(Ticket)行上收到错误,该类型不适用于参数。

public class WsTicketManagementBackend implements TicketManagementBackend {
    HashMap<Integer, Ticket> localTicketStore = new HashMap<>();
    AtomicInteger nextId;


    WsTicketServiceService client;
    WsTicketService service;

    public WsTicketManagementBackend() {
        nextId = new AtomicInteger(1);

        this.client = new WsTicketServiceService();
        service = client.getWsTicketServicePort();
    }

    @Override
    public void triggerShutdown() {

    }

    @Override
    public Ticket createNewTicket(String reporter, String topic, String description, Type type, Priority priority) {
        Ticket ticket = new Ticket(nextId.getAndIncrement(), reporter, topic, description, type, priority);
        localTicketStore.put(ticket.getId(), ticket);
        service.createTicket(ticket);
        return (Ticket) ticket.clone();
    }

此界面由wsimport工具生成:

public interface WsTicketService {


    /**
     * 
     * @param arg0
     */
    @WebMethod
    @RequestWrapper(localName = "createTicket", targetNamespace = "http://implementation.remote.ws.backend.rz.uniba.de/", className = "de.uniba.rz.backend.ws.remote.implementation.CreateTicket")
    @ResponseWrapper(localName = "createTicketResponse", targetNamespace = "http://implementation.remote.ws.backend.rz.uniba.de/", className = "de.uniba.rz.backend.ws.remote.implementation.CreateTicketResponse")
    @Action(input = "http://implementation.remote.ws.backend.rz.uniba.de/WsTicketService/createTicketRequest", output = "http://implementation.remote.ws.backend.rz.uniba.de/WsTicketService/createTicketResponse")
    public void createTicket(
        @WebParam(name = "arg0", targetNamespace = "")
        Ticket arg0);

}

2 个答案:

答案 0 :(得分:0)

您可以尝试发送带有Ticket对象属性的json字符串,然后创建它,如下所示:

createTicket(String jsonTicket){
// Instantiate a jsonObject (you can use any json library you want, I recommend PrimeFaces JSONObject)
JSONObject json = new JSONObject(jsonTicket);
// So here you make a new ticket
Ticket ticket = new Ticket();
// Set the properties of the ticket to each attribute of your json
ticket.setName(json.getString("name"));
// and so on
}

答案 1 :(得分:0)

我使用JAXB解决了这个问题,方法是将Java对象在客户端编组为xml文档,然后在Web服务器端解组回到Java对象。