gpt4 book ai didi

java - 学生编辑不行(Java + Spring + MySQl)?

转载 作者:太空宇宙 更新时间:2023-11-04 09:33:54 26 4
gpt4 key购买 nike

我有一份学生名单。我想做编辑。更改名字、姓氏和头像。我写了代码,但它不起作用,数据没有被编辑。你可以明白为什么它对我不起作用。没有错误,它只是没有改变任何东西。编辑名字后姓氏和头像不变

学生服务

public interface StudentService {

List<Student> getAllStudents();

Student getStudentById(Long id);

boolean saveStudent(Student student);

boolean deleteStudentById(Long id);

File loadAvatarByFileName(String filename);

File saveAvatarImage(MultipartFile avatarImage) throws IOException;

Student updateStudent(String name, String surname, MultipartFile avatar, Student targetStudent) throws IOException;
}

学生服务实现

@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);

}

String oldAvatarName = targetStudent.getAvatar();

if (oldAvatarName != null) {
Files.deleteIfExists(Paths.get(storageLocation + File.separator + oldAvatarName));
}

File newAvatar = null;
if (avatar != null) {
newAvatar = saveAvatarImage(avatar);
assert newAvatar != null;
targetStudent.setAvatar(newAvatar.getName());
}

boolean isSaved = saveStudent(targetStudent);

if (!isSaved) {

throw new IOException();

}

Files.deleteIfExists(Paths.get(storageLocation + File.separator + oldAvatarName));

return targetStudent;

}

学生 Controller

package adil.java.schoolmaven.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletContext;
import adil.java.schoolmaven.entity.Student;
import adil.java.schoolmaven.service.StudentService;
import java.nio.file.FileSystemException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@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;
}



@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;

}

}

编辑学生 JSP

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

<title>Home</title>
</head>
<body>

<center>
<h1>${headerMessage}</h1>


<form:form method="POST" action="${pageContext.request.contextPath}/editStudent" enctype="multipart/form-data">
<table>
<input type="hidden" value="${student.id}" name="id"/>
<tr>

<td><label path="Name">Name</label></td>
<td><input type="text" name="name" value="${student.name}"/></td>
</tr>
<tr>
<td><label path="Surname">Surname</label></td>
<td><input name="surname" value="${student.surname}"/></td>
</tr>
<tr>
<td><label path="Avatar">Avatar:</label></td>
<td>
<img src="${pageContext.request.contextPath}/avatar?avatar=${student.avatar}"
style="max-height: 200px; max-width: 200px;"/>
</td>
<td>
<input type="file" name="avatar"/>
</td>
</tr>
<tr>
<td><input class="btn btn-primary" type="submit" value="Save"></td>
</tr>
</table>
</form:form>
</center>
</body>
</html>

我的日志

(根据谷歌翻译,错误消息翻译为“该进程无法访问该文件,因为该文件正在被另一个进程使用。”)

java.nio.file.FileSystemException: C:\Pictures\avatar3435295369309803118.jpg: Процесс не может получить доступ к файлу, так как этот файл занят другим процессом.

at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:86)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
at sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:269)
at sun.nio.fs.AbstractFileSystemProvider.deleteIfExists(AbstractFileSystemProvider.java:108)
at java.nio.file.Files.deleteIfExists(Files.java:1165)
at adil.java.schoolmaven.service.StudentServiceImpl.updateStudent(StudentServiceImpl.java:122)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:338)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy402.updateStudent(Unknown Source)
at adil.java.schoolmaven.controller.StudentController.saveEditedUser(StudentController.java:98)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:870)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.sitemesh.webapp.contentfilter.ContentBufferingFilter.bufferAndPostProcess(ContentBufferingFilter.java:169)
at org.sitemesh.webapp.contentfilter.ContentBufferingFilter.doFilter(ContentBufferingFilter.java:126)
Hibernate:
select

最佳答案

该错误表明另一个进程正在使用该文件,因此无法删除该文件。

您是否在另一个程序中打开了给定的文件?

当您尝试删除文件时,您的代码是否会打开该文件/使其在其他位置保持打开状态?

我看到您的 StudentServiceImpl.updateStudent 正在调用 Files.deleteIfExists(Paths.get(storageLocation + File.separator + oldAvatarName)); 两次。根据堆栈跟踪,有问题的行是 StudentServiceImpl.java:122。两行中哪一行的数字是 122?

关于java - 学生编辑不行(Java + Spring + MySQl)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56746869/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com