Цель варианта использования — добавить новую категорию (идентификатор, имя, изображение и логическое значение).
Объект категории:
Код: Выделить всё
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String image;
private Boolean isActive;
}
Код: Выделить всё
@PostMapping("/admin/category/add")
public String saveCategory(@ModelAttribute Category category, @RequestParam("image") MultipartFile file,
HttpSession session) throws IOException {
String imageName = file != null ? file.getOriginalFilename() : "default.jpg";
category.setImage(imageName);
Boolean existCategory = categoryService.existCategory(category.getName());
if (existCategory) {
session.setAttribute("errorMsg", "Category Name already exists");
} else {
Category saveCategory = categoryService.save(category);
if (ObjectUtils.isEmpty(saveCategory)) {
session.setAttribute("errorMsg", "Not saved ! internal server error");
} else {
File saveFile = new ClassPathResource("static/img").getFile();
Path path = Paths.get(saveFile.getAbsolutePath() + File.separator + "category_img" + File.separator
+ file.getOriginalFilename());
// System.out.println(path);
Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
session.setAttribute("succMsg", "Saved successfully");
}
}
return "redirect:/admin/category";
}
Код: Выделить всё
Enter Category
Status
Active
Inactive
Upload Image
Save
Код: Выделить всё
There was an unexpected error (type=Bad Request, status=400).
Validation failed for object='category'. Error count: 1
org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public java.lang.String com.sap.Shopping.Cart.controller.AdminController.saveCategory(com.sap.Shopping.Cart.model.Category,org.springframework.web.multipart.MultipartFile,jakarta.servlet.http.HttpSession) throws java.io.IOException: [Field error in object 'category' on field 'image': rejected value [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@4d93b804]; codes [typeMismatch.category.image,typeMismatch.image,typeMismatch.java.lang.String,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [category.image,image]; arguments []; default message [image]]; default message [Failed to convert property value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'java.lang.String' for property 'image'; Cannot convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'java.lang.String' for property 'image': no matching editors or conversion strategy found]]
Подробнее здесь: https://stackoverflow.com/questions/790 ... -exception
Мобильная версия