I created a project where you can add a student with an avatar and without an avatar. The problem is that when I add a student without an avatar, there is still a tag. How can I remove the tag. Now I will add an image and a couple of classes. I kind of wrote everything correctly, I don’t know where the error might be
@Controller
public class AvatarController {
@Value("${storage.location}")
private String storageLocation;
private StudentService studentService;
@Autowired
private ServletContext servletContext;
// Constructor based Dependency Injection
@Autowired
public AvatarController(StudentService studentService) {
this.studentService = studentService;
}
@GetMapping(value = "/avatar")
public void getAvatar(HttpServletResponse response, @Param("avatar") String avatar) {
if (avatar == null || avatar.isEmpty()) {
return;
}
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
try (FileInputStream input = new FileInputStream(studentService.loadAvatarByFileName(avatar))){
IOUtils.copy(input, response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
@RequestMapping(value = "/image", method = RequestMethod.GET)
public void image(@RequestParam String url, HttpServletResponse response) throws IOException {
InputStream in = new FileInputStream(url);
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
IOUtils.copy(in, response.getOutputStream());
}
}
Image
Student Service Impl
@Service
@Transactional
public class StudentServiceImpl implements StudentService {
@Value("${storage.location}")
private String storageLocation;
private StudentRepository repository;
public StudentServiceImpl() {
}
@Autowired
public StudentServiceImpl(StudentRepository repository) {
super();
this.repository = repository;
}
@Override
public List<Student> getAllStudents() {
List<Student> list = new ArrayList<Student>();
repository.findAll().forEach(e -> list.add(e));
return list;
}
@Override
public Student getStudentById(Long id) {
Student student = repository.findById(id).get();
return student;
}
@Override
public boolean saveStudent(Student student) {
try {
repository.save(student);
return true;
} catch (Exception ex) {
return false;
}
}
@Override
public boolean deleteStudentById(Long id) {
try {
repository.deleteById(id);
return true;
} catch (Exception ex) {
return false;
}
}
@Override
public File loadAvatarByFileName(String filename) {
return new File(storageLocation + "/" + filename);
}
@Override
public File saveAvatarImage(MultipartFile avatarImage) throws IOException {
File newFile = File.createTempFile(
avatarImage.getName(),
"." + avatarImage.getOriginalFilename().split("\\.")[1],
new File(storageLocation));
avatarImage.transferTo(newFile);
return newFile;
}
@Override
public Student updateStudent(String name, String surname, MultipartFile avatar, Student targetStudent)
throws IOException {
if (name != null && !name.equals(targetStudent.getName())) {
targetStudent.setName(name);
}
if (surname != null && !surname.equals(targetStudent.getSurname())) {
targetStudent.setSurname(surname);
}
File newAvatar;
if (!avatar.getOriginalFilename().isEmpty()) {
if (targetStudent.getAvatar() != null) {
Files.deleteIfExists(Paths.get(storageLocation + File.separator + targetStudent.getAvatar()));
}
newAvatar = saveAvatarImage(avatar);
assert newAvatar != null;
targetStudent.setAvatar(newAvatar.getName());
}
boolean isSaved = saveStudent(targetStudent);
if (!isSaved) {
throw new IOException();
}
return targetStudent;
}
}
Student Controller
@Controller
public class StudentController {
@Autowired
private ServletContext servletContext;
// Constructor based Dependency Injection
private StudentService studentService;
public StudentController() {
}
@Autowired
public StudentController(StudentService studentService) {
this.studentService = studentService;
}
@RequestMapping(value = "/allStudents", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUser() {
System.out.println("User Page Requested : All Students");
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudents");
return mv;
}
@Secured("ROLE_ADMIN")
@RequestMapping(value = "/allStudentsAdmin", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUsers() {
System.out.println("User Page Requested : All Students");
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudentsUser");
return mv;
}
@Secured("ROLE_USER")
@RequestMapping(value = "/allStudentsUser", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUsers() {
System.out.println("User Page Requested : All Students");
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudentsUser");
return mv;
}
@RequestMapping(value = "/addStudent", method = RequestMethod.GET)
public ModelAndView displayNewUserForm() {
ModelAndView mv = new ModelAndView("addStudent");
mv.addObject("headerMessage", "Add Student Details");
mv.addObject("student", new Student());
return mv;
}
@PostMapping(value = "/addStudent")
public String saveNewStudent(@RequestParam("name") @NonNull String name,
@RequestParam("surname") @NonNull String surname,
@RequestParam("avatar") MultipartFile file)
throws IOException {
Student student = new Student();
student.setSurname(surname);
student.setName(name);
if (file != null && !file.isEmpty()) {
student.setAvatar(studentService.saveAvatarImage(file).getName());
}
studentService.saveStudent(student);
return "redirect:/allStudents";
}
@GetMapping(value = "/editStudent/{id}")
public ModelAndView displayEditUserForm(@PathVariable Long id) {
ModelAndView mv = new ModelAndView("editStudent");
Student student = studentService.getStudentById(id);
mv.addObject("headerMessage", "Редактирование студента");
mv.addObject("student", student);
return mv;
}
@PostMapping(value = "/editStudent")
public String saveEditedUser(
@RequestParam("id") Long id,
@RequestParam("name") String name,
@RequestParam("surname") String surname,
@RequestParam("avatar") MultipartFile file) {
try {
studentService.updateStudent(name, surname, file, studentService.getStudentById(id));
} catch (FileSystemException ex) {
ex.printStackTrace();
} catch (IOException e) {
return "redirect:/error";
}
return "redirect:/allStudents";
}
@GetMapping(value = "/deleteStudent/{id}")
public ModelAndView deleteUserById(@PathVariable Long id) {
studentService.deleteStudentById(id);
ModelAndView mv = new ModelAndView("redirect:/allStudents");
return mv;
}
}
Aucun commentaire:
Enregistrer un commentaire