Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在SpringMVC中向服务器发送用户表单数据_Java_Json_Forms_Rest_Spring Mvc - Fatal编程技术网

Java 如何在SpringMVC中向服务器发送用户表单数据

Java 如何在SpringMVC中向服务器发送用户表单数据,java,json,forms,rest,spring-mvc,Java,Json,Forms,Rest,Spring Mvc,我有一个这样的登录表单: <form:form modelAttribute="user" method="post" enctype="application/x-www-form-urlencoded"> <form:input path="userEmailId" /> <form:password path="userPassword /> <input type="

我有一个这样的登录表单:

<form:form modelAttribute="user" method="post" enctype="application/x-www-form-urlencoded">
                <form:input path="userEmailId"  />
                <form:password path="userPassword />
       <input type="submit" value="sign up" />
 </form:form> 

单击“注册”后,我希望首先将该值转换为json,然后通过post方法将该值发送到服务器。我想使用
restfulweb
服务来实现这一点。对此有何想法?

您可以使用
JSON
将表单序列化为
JSON对象,然后使用
AJAX
向web服务发送post请求:

$(function() {
    $('#formId').submit(function(event) {
        event.preventDefault(); // prevent this form from being submited
        var userJson = JSON.stringify(jQuery('#formId').serializeArray());
        $.ajax({
            type: "POST",
            url: "/Path/To/Your/Web/Service",
            data: userJson,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data){
                 alert(data);//handle it in a proper way
            },
            failure: function(errMsg) {
               alert(errMsg);//handle it in a proper way
            }
        });
        return false;
    });
});
然后在您的Web服务上,您应该有一个方法来处理此post请求:

@Controller
@RequestMapping("/path/to/your/web/service")
public class WebServiceController{

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResponseEntity<String> handleLogin(@RequestBody User user){
         //user contains data passed from UI form. Check it against your repository(database ? )

    }
}
@控制器
@请求映射(“/path/to/your/web/service”)
公共类WebServiceController{
@RequestMapping(value=“/login”,method=RequestMethod.POST)
公共响应handleLogin(@RequestBody User){
//用户包含从UI表单传递的数据。请对照您的存储库(数据库?)进行检查
}
}

请注意,这个示例只是一个简单的示例,它没有考虑与安全性相关的任何方面。

,是否可以将此json对象转换回java..?我应该在何处提供此javascript文件的引用。在jsp页面..或某处..?@aarohimeshram
@RequestBody User
将处理此转换,或者你可以添加注释
@JsonAutoDetect
i用户类,我应该把这个ajax调用代码放在哪里?很抱歉,我对这个春季mvc非常陌生。@aarohimeshram这应该在Jsp或js文件中。$(form)。serializeArray()需要更多的工作才能输出json对象,因为你想让它在另一端。。。
function getFormData($form){         
 // Make sure the checked checkboxes value is true
 $.each($form.find("input[type='checkbox']:checked"), function(i, c){
    $(c).val(true);  
 });         

 // Serialize
 var unindexed_array = $form.serializeArray();
 var indexed_array = {};

 $.map(unindexed_array, function(n, i){
     if(indexed_array[n['name']]){
         // concat
         var valueArray = [indexed_array[n['name']]];
         indexed_array[n['name']] = valueArray.concat(n['value']);
     } else {
         indexed_array[n['name']] = n['value'];
     }

 });

 // Add the unchecked checkboxes
 $.each($form.find("input[type='checkbox']:not(:checked)"), function(i, c){
     indexed_array[$(c).attr('name')] = "false";
 });

 return indexed_array;
 }

//...
$.ajax({                 
            url: entityUrl,
            method: "POST",
            contentType: "application/json",
            data: JSON.stringify(getFormData($(form))),             
            dataType: "json",               
            success: success,
            error: error
        }); 
function getFormData($form){         
 // Make sure the checked checkboxes value is true
 $.each($form.find("input[type='checkbox']:checked"), function(i, c){
    $(c).val(true);  
 });         

 // Serialize
 var unindexed_array = $form.serializeArray();
 var indexed_array = {};

 $.map(unindexed_array, function(n, i){
     if(indexed_array[n['name']]){
         // concat
         var valueArray = [indexed_array[n['name']]];
         indexed_array[n['name']] = valueArray.concat(n['value']);
     } else {
         indexed_array[n['name']] = n['value'];
     }

 });

 // Add the unchecked checkboxes
 $.each($form.find("input[type='checkbox']:not(:checked)"), function(i, c){
     indexed_array[$(c).attr('name')] = "false";
 });

 return indexed_array;
 }

//...
$.ajax({                 
            url: entityUrl,
            method: "POST",
            contentType: "application/json",
            data: JSON.stringify(getFormData($(form))),             
            dataType: "json",               
            success: success,
            error: error
        });