我试图使一种形式,用户可以添加一个产品及其形象。我使用的是springmvc。问题是,当我以html格式输入数据时,该格式是使用javascript生成的,并且尝试使用ajax发送数据时,productdto变量中的控制器没有接收到数据。我把它弄空了。我正在使用 @ModalAttribute
但它不起作用。我做错什么了?
控制器
@ResponseBody
@RequestMapping(path="/saveProduct", method = RequestMethod.POST )
public APIResponseModel saveProduct(@ModelAttribute ProductDTO productDto, HttpSession session) {
APIResponseModel apiResponseModel = new Utils().getDefaultApiResponse();
UserModel user = (UserModel) session.getAttribute("loggedInUser");
BindingResult errorList = new DataBinder(new Object()).getBindingResult();
logger.info("------------------------------------Logged In user info----------------------------------------------------");
logger.info(user);
logger.info("--"+productDto);
logger.info("----------------------------------------------------------------------------------------");
if(productDto != null && productDto.getBrand() != null) {
productServ = new ProductServiceImpl();
productServ.SaveProduct(productDto, user, null, errorList);
if(!errorList.hasErrors()) {
apiResponseModel.setStatus(HttpStatus.OK);
apiResponseModel.setData(productDto.toString());
apiResponseModel.setMessage("Product Saved Successfully !!");
}else {
errorList.addError(new ObjectError("error", "Please fill the mandatory fields"));
apiResponseModel.setMessage("Please fill the mandatory fields");
}
}else {
errorList.addError(new ObjectError("error", "Please fill the mandatory fields"));
apiResponseModel.setMessage("Please fill the mandatory fields");
}
logger.info(apiResponseModel);
return apiResponseModel;
}
控制器中使用的产品dto
package com.Indoera.DTO;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
import com.Indoera.Modal.UserModel;
public class ProductDTO {
private Integer id;
private Integer type;
private Integer gender;
private Integer quantity;
private String brand;
private Double price;
private String description;
private Integer market;
private MultipartFile mainPic;
private List<MultipartFile> additionalImages;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public MultipartFile getMainPic() {
return mainPic;
}
public void setMainPic(MultipartFile mainPic) {
this.mainPic = mainPic;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getMarket() {
return market;
}
public void setMarket(Integer market) {
this.market = market;
}
public List<MultipartFile> getAdditionalImages() {
return additionalImages;
}
public void setAdditionalImages(List<MultipartFile> additionalImages) {
this.additionalImages = additionalImages;
}
@Override
public String toString() {
return "{\"id\":\"" + id + "\", \"type\":\"" + type + "\", \"gender\":\"" + gender + "\", \"quantity\":\""
+ quantity + "\", \"brand\":\"" + brand + "\", \"price\":\"" + price + "\", \"description\":\""
+ description + "\", \"market\":\"" + market + "\", \"mainPic\":\"" + mainPic
+ "\", \"additionalImages\":\"" + additionalImages + "\"}";
}
}
生成表单并将数据发送到控制器的代码
function addProductForm(){
htmlForm ="";
htmlForm += "<div class=\"main-div\">"
+"<form>"
+"<input class=\"form-control\" id=\"brand\" type=\"text\" placeholder=\"Brand name\">"
+"<div class=\"form-group col-md-4\">"
+"<label for=\"inputGender\">Gender</label> <select id=\"gender\" class=\"form-control\" required>"
+"<option selected value=\"0\">Male</option>"
+"<option value=\"1\">Female</option>"
+"<option value=\"2\">Others</option>"
+"</select>"
+"</div>"
+"<input class=\"form-control\" id=\"price\" type=\"number\" placeholder=\"Price\">"
+"<input class=\"form-control\" id=\"quantity\" type=\"number\" placeholder=\"Quantity\">"
+"<div class=\"form-group col-md-4\">"
+"<label for=\"input\">Cloth Type</label> <select id=\"type\" class=\"form-control\" required>"
+"<option selected value=\"0\">JEANS</option>"
+"<option value=\"1\">TOP</option>"
+"<option value=\"2\">SHOES</option>"
+"<option value=\"3\">SHIRTS</option>"
+"<option value=\"4\">SLIPPERS</option>"
+"<option value=\"5\">JACKETS</option>"
+"<option value=\"6\">SWEATER</option>"
+"<option value=\"7\">SWEATSHIRTS</option>"
+"</select>"
+"</div>"
+"<div class=\"form-group\">"
+"<label for=\"description\">Decsription</label>"
+"<textarea class=\"form-control\" id=\"description\" rows=\"3\"></textarea>"
+ "</div>"
+"<div class=\"form-group\">"
+"<label for=\"mainPic\">Display Picture</label>"
+" <input type=\"file\" class=\"form-control-file\" id=\"mainPic\">"
+"</div>"
+"<div class=\"form-group col-md-4\">"
+"<label for=\"market\">Market</label> <select id=\"market\" class=\"form-control\" required>"
+"<option selected value=\"0\">SAROJANI NAGAR</option>"
+"<option value=\"1\">PALIKA</option>"
+"<option value=\"2\">RAJPATH</option>"
+"</select>"
+"</div>"
+"<button type=\"button\" class=\"btn btn-primary\" onclick=\"saveProductInfo()\">Save Product</button>"
+"</form>"
+"</div>";
document.getElementById("storeOwnerContent").innerHTML = htmlForm;
}
function saveProductInfo(){
let formData = new FormData();
formData.append("brand", $("#brand").val());
formData.append("type", $("#type").val());
formData.append("gender", $("#gender").val());
formData.append("quantity", $("#quantity").val());
formData.append("price", $("#price").val());
formData.append("description", $("#description").val());
formData.append("market", $("#market").val());
formData.append("mainPic", $("#mainPic").val());
var obj = new MasterAjax();
obj.requestType = "POST";
obj.url = "saveProduct";
obj.data = formData;
console.log("---------------------------")
for (var pair of formData.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
console.log("---------------------------")
obj.enctype ="multipart/form-data";
// obj.contentType =false;
obj.requestData(function(responseData){
console.log(responseData);
console.log("Response Data ----------------- : "+responseData.status);
if(responseData.status == "OK"||responseData.status == "ok"){
alert("success");
}else{
alert("Save failed");
}
});
}
ajax请求中使用的主ajax类
class MasterAjax{
constructor(){
this.requestType = null;
this.url = null;
this.timeout = 100000;
this.enctype = null;
this.data = null;
this.processData = null;
this.contentType = null;
this.responseData = null;
this.responseStatus = null;
this.responseStatusCode = null;
}
requestData(callBack){
var parameterError=false;
if(null == this.requestType){
parameterError=true;
console.log("Error: Request Type can't be null");
}
if(null === this.url || undefined === this.url || "undefined" === this.url){
parameterError=true;
console.log("Error: URL can't be null");
}
if(null == this.data || this.data.length <= 0){
console.log("Warning: Data is null");
}
if(parameterError === false){
/*toggleSpinnerOn(); */
$.ajax({
type : this.requestType,
enctype : this.enctype,
processData : this.processData,
contentType : this.contentType,
url : global_contextPath+"/"+this.url,
data: this.data,
timeout : this.timeout,
success : function(responseData,textStatus) {
/*toggleSpinnerOff();*/
callBack(responseData,textStatus);
},
error : function(responseData,textStatus) {
/*toggleSpinnerOff(); */
callBack(responseData,textStatus);
}
});
}
return this.responseData;
}
}
表单的jsp页面
<%@include file="/WEB-INF/views/template/Header.jsp"%>
<%@include file="/WEB-INF/views/template/ToIncludeConstants.jsp"%>
<div class="containers storeOwner" id="demo">
<div id="StoreSidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<a href="#" onclick="addProductForm()">Add Product</a>
<a href="#">Products</a>
<a href="#">Reports</a>
<a href="#">Contact</a>
</div>
<!-- Use any element to open the sidenav -->
<span onclick="openNav()"><i class="fas fa-bars"></i></span>
<!-- Add all page content inside this div if you want the side nav to push page content to the right (not used if you only want the sidenav to sit on top of the page -->
<div id="storeOwnerContent">
</div>
</div>
暂无答案!
目前还没有任何答案,快来回答吧!