当我试图保存产品并向我的保存产品控制器发出ajax请求时,我正在尝试制作一个购物应用程序控制器没有被调用,浏览器控制台上出现400(错误请求)错误。
主控制器代码:
@Controller
@RequestMapping("/")
public class MainController {
private static final Logger logger = LogManager.getLogger(MainController.class.getName());
public static String loginPage = "login/login";
public static String signUpPage = "login/signUp";
ProductService productServ;
UserService userService;
@RequestMapping("/")
public String viewPage() {
return "landing";
}
@RequestMapping("/login")
public String viewLoginPage() {
return loginPage;
}
@RequestMapping("/Register")
public String viewRegisterPage() {
return signUpPage;
}
@RequestMapping(path= "/ValidateLogin" , method = RequestMethod.POST)
public String ValidateLogin(@ModelAttribute("loginUser")UserDTO userDto, HttpSession session,BindingResult errorList) {
String returnPath="";
userService = new UserServiceImpl();
try {
// if(session.getAttribute("loggedInUser") == null){
if(Utils.isNotNull(userDto.getEmail())) {
if(Utils.isNotNull(userDto.getPassword())) {
UserModel user = userService.validateLogin(userDto, null, errorList);
if(!errorList.hasErrors()) {
user = userService.validateLogin(userDto, null, errorList);
if(!errorList.hasErrors()) {
session.setAttribute("loggedInUser", user);
if(user.getRole() == Constants.UserRole.ADMIN) {
returnPath = "Admin";
}else if(user.getRole() == Constants.UserRole.STORE_MANAGER) {
returnPath = "StoreOwner";
}else {
returnPath = "landing";
}
}else {
returnPath = loginPage;
}
}else {
returnPath =loginPage;
}
}else {
returnPath =loginPage;
errorList.addError(new ObjectError("error","Please Enter the Password!!"));
}
}else {
returnPath =loginPage;
errorList.addError(new ObjectError("error","Email is Required"));
}
// }else {
// logger.info("You are already logged in!! ");
// }
}catch(Exception e) {
e.printStackTrace();
errorList.addError(new ObjectError("error", "Somthing went wrong please try again"));
}
logger.info("--------------------Logged in USer is ------------------- : "+session.getAttribute("loggedInUser"));
return returnPath;
}
@ResponseBody
@RequestMapping(path="/saveUser" , method = RequestMethod.POST)
public APIResponseModel saveUser(@ModelAttribute UserModel user , HttpSession session , BindingResult errorList) {
APIResponseModel apiResponseModel = new Utils().getDefaultApiResponse();
try {
if(Utils.isNotNull(user)) {
userService = new UserServiceImpl();
userService.SaveUpdateUser(user, null, errorList);
if(!errorList.hasErrors()) {
session.setAttribute("loggedInUser", user);
apiResponseModel.setStatus(HttpStatus.OK);
apiResponseModel.setMessage("Saved Successfully");
apiResponseModel.setData(user.toString());
}else {
apiResponseModel.setMessage("Got Error for "+ errorList);
}
}else {
errorList.addError(new ObjectError("error", "Please Enter All the Mandatory Fields "));
apiResponseModel.setMessage("Please Enter All the Mandatory Fields");
}
}catch(Exception e) {
e.printStackTrace();
logger.info("Exception Occured because of : "+ e.getMessage());
}
logger.info(apiResponseModel);
return apiResponseModel;
}
@ResponseBody
@RequestMapping(path="/saveProduct", method = RequestMethod.POST , consumes = {"multipart/form-data"})
public APIResponseModel saveProduct(@ModelAttribute ProductDTO productDto, HttpSession session) {
logger.info("I am called !!");
APIResponseModel apiResponseModel = new Utils().getDefaultApiResponse();
UserModel user = new UserModel();
BindingResult errorList = new DataBinder(new Object()).getBindingResult();
logger.info("------------------------------------Logged In user info----------------------------------------------------");
logger.info(user);
logger.info("----------------------------------------------------------------------------------------");
if(Utils.isNotNull(productDto)) {
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"));
}
}else {
errorList.addError(new ObjectError("error", "Please fill the mandatory fields"));
}
return apiResponseModel;
}
实体类代码
@Entity
@Table(name="product_clothes")
public class ProductModal {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private Integer id;
@Column(name="brand")
private String brand;
@Column(name="gender")
private Integer gender;
@Column(name="price")
private Double price;
@Column(name="quantity")
private Integer quantity;
@Column(name="addedAt")
private Timestamp addedAt;
// @Column(name="added_By")
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name="added_By",referencedColumnName = "id")
private UserModel addedBy;
@Column(name="type")
private Integer type;
@Column(name="description")
private String description;
@Column(name="main_display_pic")
private String mainPic;
@Column(name="present_in_market")
private Integer market;
public ProductModal() {
}
public ProductModal(String brand, Integer gender, Double price, Integer quantity, Timestamp addedAt,
UserModel addedBy, Integer type, String description, String mainPic, Integer market) {
this.brand = brand;
this.gender = gender;
this.price = price;
this.quantity = quantity;
this.addedAt = addedAt;
this.addedBy = addedBy;
this.type = type;
this.description = description;
this.mainPic = mainPic;
this.market = market;
}
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 String getMainPic() {
return mainPic;
}
public void setMainPic(String 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 UserModel getAddedBy() {
return addedBy;
}
public void setAddedBy(UserModel addedBy) {
this.addedBy = addedBy;
}
public Timestamp getAddedAt() {
return addedAt;
}
public void setAddedAt(Timestamp addedAt) {
this.addedAt = addedAt;
}
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;
}
@Override
public String toString() {
return "{\"id\":\"" + id + "\", \"brand\":\"" + brand + "\", \"gender\":\"" + gender + "\", \"price\":\""
+ price + "\", \"quantity\":\"" + quantity + "\", \"addedAt\":\"" + (Hibernate.isInitialized(addedBy) ? addedBy : null) + "\", \"addedBy\":\""
+ addedBy + "\", \"type\":\"" + type + "\", \"description\":\"" + description + "\", \"mainPic\":\""
+ mainPic + "\", \"market\":\"" + market + "\"}";
}
}
dto代码
public class ProductDTO {
private Integer id;
private Integer type;
private Integer gender;
private Integer quantity;
private String brand;
private Double price;
private UserModel addedBy;
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 UserModel getAddedBy() {
return addedBy;
}
public void setAddedBy(UserModel addedBy) {
this.addedBy = addedBy;
}
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 + "\", \"addedBy\":\"" + addedBy
+ "\", \"description\":\"" + description + "\", \"market\":\"" + market + "\", \"mainPic\":\"" + mainPic
+ "\", \"additionalImages\":\"" + additionalImages + "\"}";
}
}
产品形式和ajax reuqest代码:
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>"
+"<Input type=\"button\" onclick=\"saveProductInfo()\" value= \"Save Product\" class=\"btn btn-primary\">"
+"</form>"
+"</div>";
document.getElementById("storeOwnerContent").innerHTML = htmlForm;
}
function saveProductInfo(){
console.log("I am called ");
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());
console.log($("#brand").val());
console.log($("#type").val());
console.log($("#gender").val());
console.log($("#quantity").val());
console.log($("#price").val());
console.log($("#description").val());
console.log($("#market").val());
console.log($("#mainPic").val());
var obj = new MasterAjax();
obj.requestType = "POST";
obj.url = "saveProduct";
obj.data = formData;
obj.enctype ="multipart/form-data";
obj.contentType = false;
obj.requestData(function(responseData){
console.log(responseData);
if(responseData.status == "OK"||responseData.status == "ok"){
alert("success");
}else{
alert("Save failed");
}
});
}
请点击这里查看整个项目
提前谢谢!
暂无答案!
目前还没有任何答案,快来回答吧!