0

I wasn't able to find out proper format how to send Response back to .JSP page after POST. First, how to obtain Response from Web service to Client? Second question is how to call Client from Servlet.

hariprasad
  • 555
  • 11
  • 20

1 Answers1

0

Because second part is quite straightforward (create class instance in servlet in the proper doGet, doPost method), I will focus on the first question.

Snippet on the server side:

import java.math.BigInteger;
import java.util.List;
import java.util.logging.Logger;

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

import org.hibernate.SessionFactory;

// internal beans and classes
import com.deepam.util.BasicUtils;

import entities.CustomerRest;
import entities.DualInteger;
import entities.Dualloc;
import model.CustomerModel;
import model.DualModel;
import model.HibernateUtil;

@Path("/customer")
public class CustomerRestWS {

    private final static Logger LOGGER = Logger.getLogger(CustomerRestWS.class.getName());

    private CustomerModel cm = new CustomerModel();
    private DualModel dm = new DualModel();
    private final String CUSTSEQ = "customer_rest_seq";

    SessionFactory sessionFactory;

    /** Constructor
    */
    public CustomerRestWS() {
       super();
       LOGGER.info("***" + LOGGER.getName());
       sessionFactory = HibernateUtil.getSessionFactory();
    }

...

@GET
@Path("/findcustseq")
@Produces(MediaType.APPLICATION_XML)
public DualInteger selectCustSeq() {
    return cm.selectCustSeqNative(CUSTSEQ);
}

// post method how to save customer into DB
@POST
@Path("/create")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_JSON) // JSON is used for clearity between Consumes/Produces on the Client side
public Response create(final CustomerRest cust) throws JSONException {
    Response response;
    LOGGER.info("***" + LOGGER.getName() + " Insert Customer, id, name, last name: " + cust.getId() + ", " + cust.getFirstName() + ", " + cust.getLastName());
    try {
      cm.create(cust);
    }
    catch (Exception ex) {
      // internal error
      LOGGER.info("***" + LOGGER.getName() + " Exception: " + ex.getMessage());
      response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(Response.Status.INTERNAL_SERVER_ERROR.toString()).build();
      return response;
    }
    // created
    response = Response.status(Response.Status.CREATED)
      .entity(Response.Status.CREATED.toString()).build();
    return response;
}

...

On the Client side:

import java.text.MessageFormat;
import java.util.logging.Logger;

import javax.ws.rs.core.MediaType;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.DefaultClientConfig;

// internal beans
import entities.Customer;
import entities.DualInteger;
import entities.ListCustomers;

    public class CustomerRestfulClient {
    private final static Logger LOGGER = Logger.getLogger(CustomerRestfulClient.class.getName());

    private WebResource webresource;
    private Client client;
    private static final String BASE_URI = "http://localhost:8080/RestfulOracleServer/rest/";

    public CustomerRestfulClient() {
        // init client
        client = Client.create(new DefaultClientConfig());
        // init webresource
        webresource = client.resource(BASE_URI).path("customer");
    }

...

    /** method getCustIdXML for obtaining unique ID (from sequence) */
public DualInteger getCustIdXML() throws UniformInterfaceException {
    WebResource resource = webresource.path(MessageFormat.format("findcustseq", new Object[] {}));
    return resource.accept(MediaType.APPLICATION_XML).get(DualInteger.class);
}


/** method saveCustXML call other method to obtain unique ID, than save Bean to DB */
public ClientResponse saveCustXML(String firstName, String lastName) throws UniformInterfaceException {
    DualInteger custId = getCustIdXML();
    LOGGER.info("Seqence number: " + (custId.getSeq()));
    Customer cust = new Customer(custId.getSeq(), firstName, lastName);
    ClientResponse response = webresource.path("create").
            accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_XML).post(ClientResponse.class, cust);
    LOGGER.info("Entity: " + response.getStatus());
    return response;
}

Notice classes Response on the Server side and ClientResponse on the Client Side. Look how are treated @Consumes, @Produces annotations on server side to and accept, type methods on the Client side. There were my sources of errors. In servlet Controller for .jsp simply create Client for WS e.g. custClient = new CustomerRestfulClient(); in constructor and use the obvious methods doGet, doPost as obvious. The Servlet has its own Request, Response different from Request, Response of WS. Be carefully in MVC model, Controller is treated by server as Singleton. In concurrent environment you must keep session continuity. (The most simple way is to use local variables in methods, when it is indicated.) Links to similar topics: Is it ok by REST to return content after POST? RESTful Java Client with POST method

Community
  • 1
  • 1
hariprasad
  • 555
  • 11
  • 20