将当前页面HTML源发送到Spring MVC控制器

时间:2016-02-05 06:47:22

标签: javascript jsp spring-mvc

我正在使用Spring MVC,以下是一个方法,它将从请求中获取String或Input Stream并转换为PDF并将PDF写入respose。

public void generatePDF(RequestDTO requestUIDTO, Map<String, Object> responseMap,
        HttpServletRequest request, HttpSession session, HttpServletResponse response) {
    Document document = new Document();
    PdfWriter writer;
    try {

        writer = PdfWriter.getInstance(document, response.getOutputStream());
        document.open();
        //Here I need to get the HTML file as String or InputStream from the request.
        //For now i am getting InputStream, It may be string
        InputStream in = request.getInputStream();
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, in);
        document.close();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

现在的问题是,我不知道如何将当前呈现的页面作为HTML发送到服务器,我尝试了以下Java脚本但它无法正常工作,请求本身不会去服务器可能是因为我发送一个巨大的文件作为请求参数。

function downloadLoanForm(){
     var params = {};
     params = {
             htmlContent : "htmlContent"
     }
     handleRequest(this, params, 'generatePDF.htm', '');
}
$(document).ready(function(){
     var htmlContent = $('#mainFormId').html();
     $('#htmlContent').val(htmlContent);
});

我的问题是这个,请让我知道一种方法,将当前呈现的HTML代码作为字符串(或)流发送到服务器。

这是handleRequest()函数的Java脚本代码,

function handleRequest(obj, params, request_url, replacement_element_id,
    error_redirection, function_call_after_response) {


//check if there is any value present for the request url
if(!request_url)
{
    alert('<spring:message code="JS_MSG_PROVIDE_URL_FOR_REQUEST" text=""/>');
    return false;
}

//check if the url is an external url
if(isExternal(request_url) === true)
{
    alert('<spring:message code="JS_MSG_REQUEST_CANNOT_SENT_TO_EXTERNAL_LINK" text=""/>');
    return false;
}

//global variable for making the decision on the page redirect after the error from the server - default value is false
error_redirection       = error_redirection || false;

//variable containing the replacement element id which will be used to place the content after the response from the server
replacement_element_id  = replacement_element_id || false;

//variable to decide whether some manipulation has to be done on the response data from the server
// the response data is being sent to this function along with the replacement element id
function_call_after_response = function_call_after_response || '';

//alert(function_call_after_response+'-here');

//set the replacement element's html values to to be empty before the request is being made so as to ensure that user does not go forward without getting the correct result
if(replacement_element_id)
{
    $('#'+replacement_element_id).html("");
}

//var serializedData = Array();
var counter = 0;

//SETTING THE REQUIRED ELEMENTS VALUES TO AN JSON OBJECT FOR SENDING TO THE SERVER - the elements required for the post is passed as an array in the arguments
var serializedData = {};
$.each(params, function(key, field) {

    if($("#"+key).length > 0) {

        //field = escapeHtml(field);

        var value = $("#"+key).val();
        /*if($('input[name="'+field+'"]').length > 0)
        {
            value = $('input[name="'+field+'"]').val();
        }
        else if($('select[name="'+field+'"]').length > 0)
        {
            value = $('select[name="'+field+'"]').val();
        }
        else if($('textarea[name="'+field+'"]').length > 0)
        {
            value = $('textarea[name="'+field+'"]').val();
        }*/

        value = escapeHtml(value);

        if(value != "")
        {
            counter++;
        }

        //serializedData.field = value;
        serializedData[field] = value;

        /*
        if(counter == 0)
        {
            serializedData = field+'='+value;   
        }
        else
        {
            serializedData += '&'+field+'='+value;  
        }
        counter++;
        */
    }
});

if(counter == 0)
{
    return false;
}

serializedData.csrfToken = $('form > input[name=csrfToken]').val();

//alert($('form > input[name=csrfToken]').val());

if(isExternal(request_url) === false)
{
    $('input[name="'+$(obj).attr('name')+'"]').css('float', 'left');
    $.blockUI({ message: "<h3><img src='images/processing.gif' id='processing_plz_wait' alt='Processing...' title='Processing...' border='0' class='processing_img' /><br/><spring:message code="JS_MSG_PLEASE_WAIT" text=""/></h3>" }); 
    $(".blockOverlay").show();
    $(".blockOverlay").css("opacity", "0.6");
    $(".blockMsg").show();
    $(".blockMsg").css("opacity", "1");

    //setTimeout(function() {

        $.ajax({
            type: "POST",
            url: request_url,
            data: serializedData,
            success: function(data, status, xhr) {

                if(data) {

                    //check for some strings to validate session time out - TODO need proper validation check
                    if(data.contains("<html>") && data.contains("<head>")){

                        document.location.href = 'logout.htm';

                    } else {

                        if(replacement_element_id === false) {
                    alert('<spring:message code="JS_MSG_OPERATION_PERFORMED_SUCCESSFULLY" text=""/>');
                    return false;
                }
                        else {

                    //set the response from the server to the form display element
                    $('#'+replacement_element_id).html(data);

                    setTokenValFrmAjaxResp();

                    $('#'+replacement_element_id).find("form ").append('<input type="hidden" value="'+$('#csrfToken').val()+'" name="csrfToken">');

                    $('form > input[name=csrfToken]').val($('#csrfToken').val());

                    if(function_call_after_response != "")
                    {
                        eval(function_call_after_response);
                    }

                    return false;
                }

                    }
                }
            },

            //ERROR HANDLING AS PER THE RESPONSE FROM THE SERVER - TO DO (some extra layer of error handling to be done)
            error: function(jqXHR, exception) {
                if (jqXHR.status === 0) {
                    alert('<spring:message code="JS_MSG_NOT_ABLE_TO_CONNECT_VERIFY_NETWORK" text=""/>');
                } else if (jqXHR.status == 404) {
                    alert('<spring:message code="JS_MSG_REQUEST_PAGE_NOT_FOUND" text=""/>');

                } else if (jqXHR.status == 500) {
                    alert('<spring:message code="JS_MSG_INTERNAL_SERVER_ERROR" text=""/>');
                } else if (exception === 'parsererror') {
                    alert('<spring:message code="JS_MSG_REQUESTED_DATA_PARSE_FAILED" text=""/>');
                } else if (exception === 'timeout') {
                    alert('<spring:message code="JS_MSG_TOME_OUT_ERROR" text=""/>');
                } else if (exception === 'abort') {
                    alert('<spring:message code="JS_MSG_AJAX_REQUEST_ABORTED" text=""/>');
                } else {
                    alert('<spring:message code="JS_MSG_UNCAUGHT_ERROR" text=""/>' + jqXHR.responseText);

                    if(error_redirection === true)
                    {
                        //redirect to the corresponding error page
                        document.location.href = '';
                    }
                }

                setTokenValFrmAjaxResp();

                return false;
            }
        });

    //}, 100);
}

}

0 个答案:

没有答案