为什么不编辑学生

时间:2019-06-24 09:42:48

标签: java spring-mvc

我写了一个项目,您可以在其中添加和编辑学生。我有一个学生列表,除编辑外,所有功能均有效。我想更改姓名和姓名,头像学生,但不起作用。可以看到代码,我想我写的都正确,为什么编辑学生的功能不起作用

学生控制器

package adil.java.schoolmaven.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;
    }



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

学生服务

package adil.java.schoolmaven.service;
import java.util.List;
import adil.java.schoolmaven.entity.Student;
import java.io.File;
import java.io.IOException;
import org.springframework.web.multipart.MultipartFile;

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

学生服务Impl

package adil.java.schoolmaven.service;

import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import adil.java.schoolmaven.entity.Student;
import adil.java.schoolmaven.repository.StudentRepository;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;



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

    }


}

我添加了学生资料库

package adil.java.schoolmaven.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import adil.java.schoolmaven.entity.Student;

@Repository
public interface StudentRepository extends CrudRepository<Student, Long>{

}

1 个答案:

答案 0 :(得分:0)

从StudentServiceImpl updateStudent代码中,我可以看到您没有碰到存储库,一旦使用update方法更新了现有学生的值,就必须使用repository.save(object)保存更新后的值,已经使用存储库执行了一些数据库操作,因此您必须将更新的对象保存到数据库。