使用json和struts2返回错误消息

时间:2017-04-19 11:13:52

标签: java json jsp struts2

function calculateDateDiff(fromDate, toDate) {
    var fromDate = $('#fromDate').val();
    var toDate = $('#toDate').val();

    alert('hi' + fromDate + ' ' + toDate);
    $.ajax({
        type : 'post',
        url : 'calDuration.action',
        dataType : 'json',
        data : $('#createLeaveForm').serialize(),
        success : function(data) {
            alert('success');
            var obj = data;
            $('#leaveDuration').val(obj.effectiveLeavePeriod);
            $('#suffix').val(obj.suffixPrefix);
              var actionErrs= (data.actionErrors); // list of action errors
                var actionMsgs= (data.actionMessages); // list of action messages
                var fielderror= (data.fieldErrors);
                alert(actionErrs);
                alert(actionMsgs);
                alert(fielderror);


            //alert(data.effectiveLeavePeriod);
            $("#ajax_loader").hide('slow');
                showDialog(data);

                  var actionErrs= (data.actionErrors); // list of action errors
                    var actionMsgs= (data.actionMessages); // list of action messages
                    var actionFldErrs= (data.fieldErrors); // list of field errors

                   var alertMessage="";
                    var i=0;
                    for(i=0;i<actionErrs.length; i++){
                    alertMessage=alertMessage+" "+actionMessages[i];
                    }

                    alert(alertMessage);
                    document.getElementById("err").innerHTML=alertMessage;

            /* if (data.indexOf("Successfully") != -1) {
                showDialog(data);
            } else {
                showNormalDialog(data);
            } */

        },
        error :function(data) { 
            showNormalDialog(data);
            alert('Some error occured');
            }
    });
}
   <action name="calDuration" class="in.gov.cg.action.DSChipsLeaveManagementAction" method="calculateDuration">
         <interceptor-ref name="loggingStack"></interceptor-ref>
             <result name="success" type="json"></result>   
             <interceptor-ref name="jsonValidationWorkflowStack"></interceptor-ref>
             <param name="ignoreHierarchy">false</param>
            <param name="includeProperties">actionErrors\[\d+\], fieldErrors\..+$, actionMessages\[\d+\]</param>
            <result name="error" type="json">/pages/common/finishTask.jsp</result>
                </action>
public String calculateDuration() {

    String outcome = "notDone";

    JSONObject obj = new JSONObject();
    JSONArray jsonGroupListArray = new JSONArray();
    try {
        startDate = ApplicationUtil.generateDateFromString(leaveVO
                .getStartDate());
        endDate = ApplicationUtil.generateDateFromString(leaveVO
                .getEndDate());
        halfDay = ApplicationUtil.getBooleanFromDB(leaveVO
                .getHalfDayString());
        System.out.println(halfDay);

    } catch (ParseException e1) {
        e1.printStackTrace();
    }

    if (loginVO == null) {
        loginVO = (LoginUserVO) this.getSession().get("LoggedInUser");
    }

    if (startDate == null || "".equalsIgnoreCase(startDate.toString())) {
        addActionMessage(getText("error.mandatory.StartDate"));
        return "error";
    }
    if (endDate == null || "".equalsIgnoreCase(endDate.toString())) {
        addActionMessage(getText("error.mandatory.EndDate"));
        return "error";
    }
    if (startDate != null && endDate != null) {
        if (startDate.compareTo(endDate) != 0) {
            if (startDate.after(endDate)) {

                addActionMessage(getText("please select proper Date"));
                Date date = null;
                leaveVO.setToDate(date);
                return "error";
            }
        }
    }
        int holidayCount = 0;
        String totalDayCount = "";
        String userLeaveMsg = "";

        try {

            String msg = " Holiday List :";
            totalDayCount = ApplicationUtil.calculateDaydiffernce(
                    new java.sql.Timestamp(startDate.getTime()),
                    new java.sql.Timestamp(endDate.getTime()));
            if (totalDayCount.equals("")) {
                totalDayCount = "0";
            }
            holidayList = LeaveManager.getInstance()
                    .getHolidayList(loginVO);

            endDate = ApplicationUtil.getSQLDateFromUtilDate(endDate);
            startDate = ApplicationUtil.getSQLDateFromUtilDate(startDate);

            for (HolidayVO holiday : holidayList) {

                if (holiday.getCalDate().compareTo(endDate) == 0) {
                    if (holiday.isIsUserLeave()) {
                        userLeaveMsg = userLeaveMsg.concat(ApplicationUtil
                                .generateStringFromUtilDate(holiday
                                        .getCalDate()));
                    }
                }
                if (holiday.getCalDate().compareTo(
                        ApplicationUtil.getNextDate(endDate)) == 0) {

                    suffixPrefix = suffixPrefix
                            .concat("Suffix::")
                            .concat(ApplicationUtil
                                    .generateStringFromUtilDate(holiday
                                            .getCalDate())).concat(" is ")
                            .concat(holiday.getRemarks());
                    leaveVO.setSuffixPrefix(suffixPrefix);

                }

                if (startDate.compareTo(endDate) != 0) {
                    if (holiday.getCalDate().after(startDate)
                            && holiday.getCalDate().before(endDate)) {
                        msg = msg.concat(ApplicationUtil
                                .generateStringFromUtilDate(holiday
                                        .getCalDate()));
                        System.out.println(msg);

                        suffixPrefix = suffixPrefix
                                .concat("Suffix::\n")
                                .concat(ApplicationUtil
                                        .generateStringFromUtilDate(holiday
                                                .getCalDate()))
                                .concat(" is ")
                                .concat(holiday.getRemarks()).concat("\n");
                        System.out.println(suffixPrefix);
                        addActionMessage(getText(msg));
                        holidayCount++;
                        leaveVO.setSuffixPrefix(suffixPrefix);
                    }
                }
                effectiveLeavePeriod = String.valueOf(Integer
                        .valueOf(totalDayCount)
                        - Integer.valueOf(holidayCount) + 1);
                // effectiveLeavePeriod=String.valueOf(Integer.valueOf(totalDayCount)+1);
                // leaveTypeBal =
                // UserManager.getInstance().populateMasterList(loginVO);
                for (LeaveUserVO leavev : leaveBalDetail) {
                    // To check applied duration does not exceeds the
                    // current available balance
                    if (leavev.getLeaveTypeID().equals(
                            leaveVO.getLeavetype())) {
                        if (Double.valueOf(effectiveLeavePeriod) > Double
                                .valueOf(leavev.getLeaveCurrBalance())) {
                            addActionMessage(getText("levae balance is low")
                                    .concat(String
                                            .valueOf(effectiveLeavePeriod)
                                            .concat(String.valueOf(leavev
                                                    .getLeaveCurrBalance()))));
                            System.out.println("levae balance is low"
                                    + String.valueOf(leavev
                                            .getLeaveCurrBalance()));
                            // effectiveLeavePeriod = "0";
                            return "error";
                        }
                    }


                }

            }
            if (leaveVO.getLeavetype() != null
                    && leaveVO.getLeavetype().equals("14")) {
                effectiveLeavePeriod = String.valueOf(Integer
                        .valueOf(totalDayCount) + 1);
            }
        } catch (Exception e) {
            String errorTicketNumber = CommonMBeanHelper
                    .getErrorTicketNumber(e, MODULE.LEAVE);
            log.error("Error ticket number is: " + errorTicketNumber);
            log.error("Exception in init -- > ", e);

        }

        if (halfDay == true) {
            double leavePeriod = Double.valueOf(effectiveLeavePeriod);
            duration = (leavePeriod - 0.5);
            leaveVO.setLeaveDuration(duration);
            effectiveLeavePeriod = String.valueOf(leaveVO
                    .getLeaveDuration());

        } else {

            leaveVO.setLeaveDuration(Double.valueOf(effectiveLeavePeriod));
        }

        obj.put("effectiveLeavePeriod", effectiveLeavePeriod);
        obj.put("suffixPrefix", suffixPrefix);
        //obj.put("MSG", arg1)
        jsonGroupListArray.add(obj);

        System.out.printf("durationValue JSON: %s", jsonGroupListArray);
        JSONObject finalObj = new JSONObject();
        finalObj.put("data", jsonGroupListArray.toString());
        finalObj.put("status", "success"); // final jsonobject for status
        finalObj.put("message", " duration calculate.");


    return "success";
}

当我选择错误的日期或使用json和struts2没有适当的平衡时,如何返回错误消息。

我在这里finishTask.jsp宣布了addActionMessageAddErrorMessage。我只有在成功发生后才能获得持续时间。

0 个答案:

没有答案