简体   繁体   中英

JSP form values passed to a servlet

I have a form in JSP in the following manner :

<form id="provision-field" method="post" action="${pageContext.request.contextPath}/myServlet">

    <fieldset>
        <ol class="fields">

            <li>
                <label for="field1">field1</label>
                <input type="text" id="field1" "
                        value="<%= field1 %>"

                        />
                <span class="description">
                    <span class="optional">Optional</span>
                </span>
            </li>
        </ol>
    </fieldset>
    <div class="actions">
        <button type="submit" name="Submit">
            Submit form
        </button>
        <a href="" class="close-dialog">Cancel</a>
    </div>
</form>

I have a js snippet on click of the submit button does the following

var field = document.getElementById("field1").value;   

 $.ajax({
                url: '${pageContext.request.contextPath}/myServlet'
                type: 'POST',
                data: field,
                dataType: "html",
                success: function(html) {

                  alert("Success");
                },
                error: function(error){
                alert("ERROR");
                }
                });

When I just use the form element (ie take out the js code) , I can reach my servlet but none of my form parameters are passed . when I try using the js code , the ajax request does not work . could someone point to me how this should be correctly done .

The servlet code is :

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       logger.info("Inside the post function");
        logger.info(request.getParameter("data");

    }
    var field = document.getElementById("field1").value;   

    $.ajax({
        url: '${pageContext.request.contextPath}/myServlet'
        type: 'POST',
        data: {
            data :field
        },
        dataType: "html",
        success: function(html) {

          alert("Success");
        },
        error: function(error){
        alert("ERROR");
        }
    });

Inside servelt following code in doPost method : Assuming that you have primary knowledge of HttpServlet...

    request.getParameter("data");

I am sharing small Ajax with Servlet tutorial , which may help you for further problem... Download Link- AJAX Servlet Tutorial

data: { field1:field1Value } send like this

and then access request.getParameter("field1"); in servlet

由于表单提交方法是post method="post" ,因此您需要确保在doPost(request, response)方法中获取请求值

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