spring - 添加没有头像的学生

标签 spring spring-mvc

我创建了一个项目,您可以在其中添加带头像和不带头像的学生。 问题是,当我添加一个没有头像的学生时,仍然有一个标签。如何删除该标签。现在我将添加一个图像和几个类。我写的一切都正确,我不知道错误可能在哪里

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

学生服务实现

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

    }

}

学生 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;

    }

}

AllStudent JSP

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<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>
        <link href="../css/style.css" rel="stylesheet" type="text/css">
        <style><%@include file="/css/style.css"%></style>
        <title>Все студенты</title>
    </head>
    <body>
            <br>
            <br>
            <br>
            <br>
            <div class="it">
                <h3>Список всех студентов</h3>
                ${message}

                <br>
                <br>
                <table class="table">
                    <thead>
                        <tr>
                            <th scope="col">#</th>
                            <th scope="col">Name</th>

                            <th scope="col">Surname</th>
                            <th scope="col">Avatar</th>
                        </tr>
                    </thead>
                    <tbody>
                        <c:forEach var="student" items="${studentList}">
                            <tr>
                                <th scope="row">1</th>
                                <td>${student.name}</td>
                                <td>${student.surname}</td>

                                <td><c:choose>
     <c:when test="${student.avatar ne null}">
         <td>
           <img src="${pageContext.request.contextPath}/avatar?avatar=${student.avatar}" 
             style="max-height: 200px; max-width: 200px;" />
        </td>
     </c:when>

 </c:choose></td>

                                <td>
                                    <sec:authorize access="hasRole('ADMIN')">
                                        <a href="${pageContext.request.contextPath}/editStudent/${student.id}">
                                            <button type="button" class="btn btn-primary">Edit</button>
                                        </a>
                                    </sec:authorize>
                                </td>
                                <td>
                                    <sec:authorize access="hasRole('ADMIN')">
                                        <a href="${pageContext.request.contextPath}/deleteStudent/${student.id}">
                                            <button type="button" class="btn btn-primary">Delete</button>
                                        </a>
                                    </sec:authorize>
                                </td>
                            </tr>
                        </c:forEach>
                    </tbody>
                </table>

            </div>

    </body>
</html>

最佳答案

@user404 回答可以,但需要一些更改

<c:choose>
     <c:when test="${student.avatar ne null}">
         <td>
           <img src="${pageContext.request.contextPath}/avatar?avatar=${student.avatar}" 
             style="max-height: 200px; max-width: 200px;" />
        </td>
     </c:when>
     <c:otherwise>
       <td></td>
     </c:otherwise>
 </c:choose> 

despription : When avater is null or empty then add a empty cell on our html table other wise add image with full src path

关于spring - 添加没有头像的学生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56783424/

相关文章:

java - 如何在 Spring-Batch 中使用 ItemReader 跳过行?

spring - 如何使用 Spring Boot 在 H2 控制台中设置默认 JDBC URL 值

javascript - 以 HTML 格式显示上传后的 CSV 内容

java - 上传图片,编码为base64 Spring MVC

java - @WebMvcTest 失败,出现 java.lang.IllegalStateException : Failed to load ApplicationContext

java - spring mvc servlet初始化

java - 测试 applicationContext : org. springframework.core.annotation.AnnotationUtils.getAnnotationAttributes

java - Spring 数据 CRUD 方法

Spring-boot liquibase 集成

java - 请求映射中的双星号