Saturday, May 30, 2015

Example of jQuery Ajax with JSON Payload in Request and JSON Response from Servlet

Here is an example of an ajax implementation using jQuery ajax with JSON payload and a servlet  using a JSON response.

Here's what you will need in your project:

Files under Web App Libraries:
jackson-annotations-2.4.0.jar
jackson-core--2.4.2.jar
jackson-databind-2.4.2.jar

File under \WebContent\js:
jquery-1.11.1.min.js


In your web.xml
 <servlet>
  <description>
  </description>
  <display-name>IncentiveClaimAjaxServlet</display-name>
  <servlet-name>IncentiveClaimAjaxServlet</servlet-name>
  <servlet-class>com.web.servlet.IncentiveClaimAjaxServlet</servlet-class>
 </servlet> 
 
 <servlet-mapping>
  <servlet-name>IncentiveClaimAjaxServlet</servlet-name>
  <url-pattern>/IncentiveClaimAjaxServlet</url-pattern>
 </servlet-mapping> 


In external javascript (IncentiveClearinghouse.js):
function submitComment(incentiveClaim, btnElement) {
 var newComment = $("#comment-input").val();  
 
 $("#comment-input").val(""); //clear the comment textarea
 $("#dialog-form").dialog( "close" ); //close the dialog

 
 incentiveClaim.approverComments = newComment;
 //alert(JSON.stringify({incentiveClaimJSONDTO: incentiveClaim}));

    $.ajax({
        type: "POST",
        url: "/IncentiveClearinghouseWeb/IncentiveClaimAjaxServlet?queueName=" + gQueueName + "&division=" + gDivision + "&user=" + gUser,
        //For the Jackson ObjectMapper to work on the server side - the KEY you assign to the JSON object (e.g. 'incentiveClaimJSONDTO') 
        //should be the same name as the property of the Java object it will map to (e.g. 'IncentiveClaimJSONWrapper.incentiveClaimJSONDTO) 
        data: JSON.stringify({incentiveClaimJSONDTO: incentiveClaim}),  
        contentType: "application/json; charset=UTF-8",
        dataType: "json",        
        success: function(response){
         var message = response[0].message;
         if (response[0].type == "S" && incentiveClaim.claimStatus != "U") {
          //if SAP response is success and status is Approve or Reject then update the admin comments in the DOM
          updateAdminComment(newComment, btnElement);
          //and replace buttons with the response success message
          showRespMsg(message, btnElement);
         } else if (response[0].type == "S" && incentiveClaim.claimStatus == "U") {
          //if SAP response is success and status is Update then update the admin comments in the DOM
          updateAdminComment(newComment, btnElement);
         } else if (response[0].type == "E") {
          //if SAP response is error then alert the response error message
          alert('Error: \n' + message);
         }
        },
        error: function(e){
            alert('Error: \n' + e);
        }
    });  
}


In jsp (ICHClaimList.jsp):
 <td class="<c:out value="${tdClass}" />">
  <button id="approveBtn" onclick="approve('${incentiveClaimDTO.dealerId}', '${incentiveClaimDTO.incentiveType}', '${incentiveClaimDTO.invoiceNumber}', '${incentiveClaimDTO.lineNbr}', '${incentiveClaimDTO.model}', '${incentiveClaimDTO.serialNumber}', '${incentiveClaimDTO.programId}', this);">Approve</button>         
  <button id="rejectBtn"  onclick="reject('${incentiveClaimDTO.dealerId}', '${incentiveClaimDTO.incentiveType}', '${incentiveClaimDTO.invoiceNumber}', '${incentiveClaimDTO.lineNbr}', '${incentiveClaimDTO.model}', '${incentiveClaimDTO.serialNumber}', '${incentiveClaimDTO.programId}', this);">Reject</button>
  <button id="updateBtn"  onclick="update('${incentiveClaimDTO.dealerId}', '${incentiveClaimDTO.incentiveType}', '${incentiveClaimDTO.invoiceNumber}', '${incentiveClaimDTO.lineNbr}', '${incentiveClaimDTO.model}', '${incentiveClaimDTO.serialNumber}', '${incentiveClaimDTO.programId}', this);">Update</button>         
 </td>



In servlet (IncentiveClaimAjaxServlet.java):
public class IncentiveClaimAjaxServlet extends HttpServlet   {

 private static final long serialVersionUID = 1L;
 private final LogHelper LOG = new LogHelper(this.getClass());
 
 private String user;
 
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String method = "doPost()";
  LOG.debug(method, "START");  

  String queueName = request.getParameter("queueName");
  String division = request.getParameter("division");
  user = request.getParameter("user");  
  try {
   ArrayList<IncentiveClaimResponseDTO> responseList = executeTask(request);
   
   //set response type to JSON
   response.setContentType("application/json");
   response.setHeader("cache-control", "no-cache");
         //initiate jackson mapper
   ObjectMapper mapper = new ObjectMapper();
   //send the JSON response to client
   mapper.writeValue(response.getOutputStream(), responseList);
   
  } catch(Exception ex) {
   ex.printStackTrace();
   LOG.error("Exception Processing AJAX Request: " + ex.getMessage());
   throw new ServletException(ex);
  }
 }
 
 public ArrayList<IncentiveClaimResponseDTO> executeTask(HttpServletRequest request) throws IOException, ServletException {

  //get received JSON data from request
  String jsonString = "";
  try {
   jsonString = getBody(request);
  } catch (IOException ex) {
   LOG.debug("Error in retrieving the JSON payload from the request"); 
  }
  LOG.debug("--------------------------------------");
  LOG.debug("JSON: \n" + jsonString); 
     
        //initiate jackson mapper
  ObjectMapper mapper = new ObjectMapper();
  IncentiveClaimJSONWrapper incentiveClaimJSONWrapper = new IncentiveClaimJSONWrapper();
  
  IncentiveClaimService claimService = IncentiveClaimService.getInstance();
  ArrayList<IncentiveClaimResponseDTO> responseList = new ArrayList<IncentiveClaimResponseDTO>();
  try {
   //convert JSON object to java object
   incentiveClaimJSONWrapper = mapper.readValue(jsonString, IncentiveClaimJSONWrapper.class);
   IncentiveClaimJSONDTO incentiveClaimJSONDTO = incentiveClaimJSONWrapper.getIncentiveClaimJSONDTO();
   
   responseList = claimService.processIncentive(mapJsonDTOToRequest(incentiveClaimJSONDTO)); 
   
  } catch (IncentiveClearinghouseException icex) {
   //errors.add(Constants.ERROR_MSG_CONSTANTS.ACTION_PROCESSING_ERROR, new ActionMessage("errors.decision.action", "Error Code: " + icex.getErrorCode(), "Exception: " + icex.getMessage()));
   LOG.error("IncentiveDecisionAction Error: " + icex.getMessage());
   icex.printStackTrace();
  } catch (Exception ex) {   
   //errors.add(Constants.ERROR_MSG_CONSTANTS.ACTION_PROCESSING_ERROR, new ActionMessage("errors.decision.action", "Error Code: " + Constants.EXCEPTION_CONSTANTS.ACTION_EXCEPTION, "Exception: " + ex.getMessage()));
   LOG.error("IncentiveDecisionAction Error: " + ex.getMessage());
   ex.printStackTrace();
  }
  
  return responseList;

 }
 
 public String getBody(HttpServletRequest request) throws IOException {
  BufferedReader br = null;
        String json = "";
  try {
         br = request.getReader();
         if(br != null){
             json = br.readLine();
         }    
     } catch (IOException ex) {
         throw ex;
     } finally {
         if (br != null) {
             try {
              br.close();
             } catch (IOException ex) {
                 throw ex;
             }
         }
     }
  return json;
 } 
 
 
 private IncentiveClaimDTO mapJsonDTOToRequest(IncentiveClaimJSONDTO incentiveClaimJSONDTO) throws IncentiveClearinghouseException {
  IncentiveClaimDTO claimDTO = new IncentiveClaimDTO();
  
  try {   
   claimDTO.setApproverComments(incentiveClaimJSONDTO.getApproverComments());
   if( incentiveClaimJSONDTO.getDealerId() != null && !incentiveClaimJSONDTO.getDealerId().equals("") )
    claimDTO.setDealerId(Integer.parseInt(incentiveClaimJSONDTO.getDealerId()));
   claimDTO.setClaimStatus(incentiveClaimJSONDTO.getClaimStatus());
   claimDTO.setIncentiveType(incentiveClaimJSONDTO.getIncentiveType());
   claimDTO.setInvoiceNumber(incentiveClaimJSONDTO.getInvoiceNumber());
   claimDTO.setLineNbr(incentiveClaimJSONDTO.getLineNumber());
   claimDTO.setModel(incentiveClaimJSONDTO.getModel());
   claimDTO.setModUserId(user);
   claimDTO.setProgramId(incentiveClaimJSONDTO.getProgramId());
   claimDTO.setSerialNumber(incentiveClaimJSONDTO.getSerialNumber());
  } catch (Exception ex) {
   throw new IncentiveClearinghouseException(Constants.EXCEPTION_CONSTANTS.ACTION_EXCEPTION, "Exception Mapping FormBean to Request");
  }
  
  return claimDTO;
 }
 
}


The DTOs:

IncentiveClaimResponseDTO
public class IncentiveClaimResponseDTO {

    private String field;
    private String id;
    private String logMsgNo;
    private String logNo;
    private String message;
    private String messageV1;
    private String messageV2;
    private String messageV3;
    private String messageV4;
    private String number;
    private String parameter;
    private BigInteger row;
    private String system;
    private String type; 
 
 public IncentiveClaimResponseDTO() {
  
 }

  

 public String getField() {
  return field;
 }


 public String getId() {
  return id;
 }


 public String getLogMsgNo() {
  return logMsgNo;
 }


 public String getLogNo() {
  return logNo;
 }


 public String getMessage() {
  return message;
 }


 public String getMessageV1() {
  return messageV1;
 }


 public String getMessageV2() {
  return messageV2;
 }


 public String getMessageV3() {
  return messageV3;
 }


 public String getMessageV4() {
  return messageV4;
 }


 public String getNumber() {
  return number;
 }


 public String getParameter() {
  return parameter;
 }


 public BigInteger getRow() {
  return row;
 }


 public String getSystem() {
  return system;
 }


 public String getType() {
  return type;
 }


 public void setField(String field) {
  this.field = field;
 }


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


 public void setLogMsgNo(String logMsgNo) {
  this.logMsgNo = logMsgNo;
 }


 public void setLogNo(String logNo) {
  this.logNo = logNo;
 }


 public void setMessage(String message) {
  this.message = message;
 }


 public void setMessageV1(String messageV1) {
  this.messageV1 = messageV1;
 }


 public void setMessageV2(String messageV2) {
  this.messageV2 = messageV2;
 }


 public void setMessageV3(String messageV3) {
  this.messageV3 = messageV3;
 }


 public void setMessageV4(String messageV4) {
  this.messageV4 = messageV4;
 }


 public void setNumber(String number) {
  this.number = number;
 }


 public void setParameter(String parameter) {
  this.parameter = parameter;
 }


 public void setRow(BigInteger row) {
  this.row = row;
 }


 public void setSystem(String system) {
  this.system = system;
 }


 public void setType(String type) {
  this.type = type;
 }



 @Override
 public String toString() {
  return getClass().getName() + " {\n\tfield: " + field + "\n\tid: " + id
    + "\n\tlogMsgNo: " + logMsgNo + "\n\tlogNo: " + logNo
    + "\n\tmessage: " + message + "\n\tmessageV1: " + messageV1
    + "\n\tmessageV2: " + messageV2 + "\n\tmessageV3: " + messageV3
    + "\n\tmessageV4: " + messageV4 + "\n\tnumber: " + number
    + "\n\tparameter: " + parameter + "\n\trow: " + row
    + "\n\tsystem: " + system + "\n\ttype: " + type + "\n}";
 }
}


IncentiveClaimJSONWrapper
public class IncentiveClaimJSONWrapper implements Serializable {

 private static final long serialVersionUID = 4804830588834912345L;

 private IncentiveClaimJSONDTO incentiveClaimJSONDTO;

 
 
 public IncentiveClaimJSONDTO getIncentiveClaimJSONDTO() {
  return incentiveClaimJSONDTO;
 }

 public void setIncentiveClaimJSONDTO(IncentiveClaimJSONDTO incentiveClaimJSONDTO) {
  this.incentiveClaimJSONDTO = incentiveClaimJSONDTO;
 }
 
 
}


IncentiveClaimJSONDTO
public class IncentiveClaimJSONDTO implements Serializable {

 private static final long serialVersionUID = 8439021168470172893L;
 
 private String claimStatus;
 private String dealerId;
 private String incentiveType;
 private String invoiceNumber;
 private String lineNumber;
 private String model;
 private String serialNumber;
 private String programId;
 private String approverComments;
 
 
 public String getClaimStatus() {
  return claimStatus;
 }
 public void setClaimStatus(String claimStatus) {
  this.claimStatus = claimStatus;
 }
 public String getDealerId() {
  return dealerId;
 }
 public void setDealerId(String dealerId) {
  this.dealerId = dealerId;
 }
 public String getIncentiveType() {
  return incentiveType;
 }
 public void setIncentiveType(String incentiveType) {
  this.incentiveType = incentiveType;
 }
 public String getInvoiceNumber() {
  return invoiceNumber;
 }
 public void setInvoiceNumber(String invoiceNumber) {
  this.invoiceNumber = invoiceNumber;
 }
 public String getLineNumber() {
  return lineNumber;
 }
 public void setLineNumber(String lineNumber) {
  this.lineNumber = lineNumber;
 }
 public String getModel() {
  return model;
 }
 public void setModel(String model) {
  this.model = model;
 }
 public String getSerialNumber() {
  return serialNumber;
 }
 public void setSerialNumber(String serialNumber) {
  this.serialNumber = serialNumber;
 }
 public String getProgramId() {
  return programId;
 }
 public void setProgramId(String programId) {
  this.programId = programId;
 }
 public String getApproverComments() {
  return approverComments;
 }
 public void setApproverComments(String approverComments) {
  this.approverComments = approverComments;
 }
 
 
}


That's it.

No comments:

Post a Comment