简体   繁体   中英

Sending response from Jersey web service (HTTP-POST) to the client (Jquery AJAX)

This is a Jersey web service to post data to a server and store it to the database:

@Path("/add")
@POST
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response create(Resource Resource) {
    Response r = null;
    String message = "sucessfully added";
    try {
        r = Response.status(200).entity(message).build();
        ResourceDAO dao = new ResourceDAO();
        dao.createResource(Resource);
    } catch (SQLException e) {
        message = "Exception in creating new Resource " + e;
        r = Response.status(409).entity(message).build();
        e.printStackTrace();
    } catch (RuntimeException e) {
        message = "Exception in creating new Resource " + e;            
        r = Response.status(409).entity(message).build();
        e.printStackTrace();
    } catch (Exception e) {
        message = "Exception in creating new Resource " + e;
        r = Response.status(409).entity(message).build();
        e.printStackTrace();
    }

        return r;

}

Following is an AJAX client that performs the POST call:

$.ajax({
                type : "POST",
                url : "rest/network/add",
                contentType : 'application/json; charset=utf-8',
                dataType : "json",
                data : JSON.stringify(data),
                success : function(msg /*what should be over here instead of msg if I am to receive a response from the server? */) {
                    //alert: displays the response that comes from the server

                }


            });

Issue : Web service has to return the response to the ajax-client and the ajax-client has to display the response in an alert. Response if an exception is encountered(data already exists in the DB) is different from Response when there is no exception.

Question: What are the changes to be made on the server and client side codes so that sending and receiving of responses is possible?

Any help is highly appreciated. Thanks.

Have you tried with

success : function(response) {
                                alert(response.responseText); 
                            },
error : function(jqXHR, textStatus,errorThrown) {

            //here you would print the errorThrown                  

                            }

The web service looks as follows:

@Path("/add")
@POST
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response create(Resource resource) throws Exception {
    Response r = null;
    String message = null;
    System.out.println("in post");
    ResourceDAO dao = new ResourceDAO();

    message = dao.createResource(resource);
    /*this message as a function of createResource: success returns- "Created" exception returns = "Not Created"*/
    r = Response.status(200).entity(message).build();
    return r;

}

The ajax call looks like this:

$.ajax({
                type : "POST",
                url : "rest/Resource/add",
                contentType : 'application/json; charset=utf-8',
                dataType : "json",
                data : JSON.stringify(data),
                statusCode : {
                    200 : function(jqXHR) {
                        $.messager.alert('Request Status',
                                jqXHR.responseText);

                    }

                },


                error : function(jqXHR, textStatus, errorThrown) {
                    $('#createResourceDialog').dialog('close');

                    $.messager.alert('Error',
                            'Unable to connect to the server');

                }

            });

This code works fine. But it executes the

error : function(jqXHR, textStatus, errorThrown) {
                    $('#createResourceDialog').dialog('close');

                    $.messager.alert('Error',
                            'Unable to connect to the server');

                }

every single time - even after executing the statusCode block. This sounds illogical. I expect error block to execute only when the ajax call fails to communicate with the URL/server. Help needed!

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