原文出自:https://blog.csdn.net/seesun2012
原生Java+JQuery form表单serializeArray提交自动对应java实体,这是一个实际的例子:
html界面:
<form id="data-form">
秒杀一:<input class="td_input" name="killA" type="number"><br>
秒杀二:<input class="td_input" name="killB" type="number"><br>
秒杀三:<input class="td_input" name="killC" type="number"><br>
秒杀四:<input class="td_input" name="killD" type="number"><br>
</form>
<div>
<span id = "killApple" style="padding: 20px;">开始秒杀</span>
</div>
JS脚本,表单序列化 + 异步请求:
//点击提交,发送异步请求
$("#killApple").click(function(content){
//获取表单数据,并序列化
var formData = $("#flop-form").serializeArray();
//将序列化数据转为对象
var formObject = {};
for (var item in formData) {
formObject[formData[item].name] = formData[item].value;
}
formData = JSON.stringify(formObject);
//发送JSON到服务器
$.ajax({
type: "POST",
url: "/kill/killOrder",
contentType: "application/json", //一定要设置这一行,很关键
data : formData,
datatype: "json",
success: function (data) {
alert(JSON.stringify(data));
}
});
});
秒杀下单控制器:
package com.seesun2012.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.seesun2012.dao.entity.KillOrder;
import com.seesun2012.utils.Result;
/**
* 【秒杀下单】控制器
*
* @author seesun2012@163.com
*
*/
@Controller
@RequestMapping("/kill")
public class GameController extends BaseController{
/**
* 衬衫秒杀
*/
@RequestMapping(value = "/killApple", method = RequestMethod.POST, consumes = "application/json")
@ResponseBody
public Result killOrder(HttpServletRequest request, @RequestBody KillOrder ko){
try {
//具体业务实现
return Result.build(200, "秒杀成功");
} catch (Exception e) {
return Result.build(500, e.getMessage());
}
}
}
秒杀实体Bean:
package com.seesun2012.dao.entity;
/**
* 秒杀参数实体
*/
public class KillOrder {
private Integer killA;
private Integer killB;
private Integer killC;
private Integer killD;
//TODO GET、SET方法...
}
秒杀结果返回工具类:
package com.seesun2012.utils;
import java.io.Serializable;
import java.util.HashMap;
/**
* 统一返回结果类
*
* @author seesun2012@163.com
*
*//
public class Result extends HashMap<String, Object> implements Serializable {
private static final long serialVersionUID = 1L;
public static final Result SUCCEED = new Result(0, "操作成功");
public Result(int status, String massage) {
super();
this.put("status", status).put("message", massage);
}
public Result put(String key, Object value) {
super.put(key, value);
return this;
}
public static Result build(int i, String message) {
return new Result(i, message);
}
}