powered by simpleCommunicator - 2.0.49     © 2025 Programmizd 02
Форумы / Java [игнор отключен] [закрыт для гостей] / Добавить студента без аватарки
11 сообщений из 11, страница 1 из 1
Добавить студента без аватарки
    #39819069
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Я написал проект где можно добавлять студента через браузер в бд MySQL. Он у меня хорошо все добавляет имя, фамилию, аватарку. Но когда я хочу просто добавить имя и фамилию он выбрасывает ошибку, как можно чтобы можно было добавлять студента через Spring без аватарки.

StudentController.

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
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.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 = {"/", "/index"}, method = RequestMethod.GET)
    public ModelAndView hello() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("index");
        return mv;
    }

    // Get All Users
    @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") String name,
            @RequestParam("surname") String surname,
            @RequestParam("avatar") MultipartFile file)
            throws IOException {

        if (file != null && !file.isEmpty()) {
            Student student = new Student();
            student.setSurname(surname);
            student.setName(name);
            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;

    }

}


StudentServiceImpl
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
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);

        }

        File newAvatar = null;

        if(avatar != null){

            newAvatar = saveAvatarImage(avatar);

        }

        assert newAvatar != null;

        String oldAvatarName = targetStudent.getAvatar();

        targetStudent.setAvatar(newAvatar.getName());

       boolean isSaved = saveStudent(targetStudent);

        if (!isSaved) {

            throw new IOException();

        }

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

        return targetStudent;

    }


}


AvatarController

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
package adil.java.schoolmaven.controller;

import adil.java.schoolmaven.service.StudentService;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;

import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.repository.query.Param;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@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) throws IOException {
        if (avatar == null || avatar.isEmpty()) {

            return;

        }

        response.setContentType(MediaType.IMAGE_JPEG_VALUE);
        IOUtils.copy(new FileInputStream(studentService.loadAvatarByFileName(avatar)), response.getOutputStream());
    }

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


AddStudentJSP

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
<%@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>

        <div class="add">
            <br>
            <br>
            <br>

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

                <form:form method="POST" action="${pageContext.request.contextPath}/addStudent" enctype="multipart/form-data">
                    <table>

                        <tr>
                            <td><label path="Name">Имя</label></td>
                            <td><input type="text" name="name"/></td>
                        </tr>
                        <tr>
                            <td><label path="Surname">Фамилия</label></td>
                            <td><input type="text" name="surname"/></td>
                        </tr>
                        <tr>
                            <td><label path="Avatar">Фотография:</label></td>
                            <td>
                                <input type="file" name="avatar"/>
                            </td>

                        </tr>
                        <tr>
                            <td><input class="btn btn-primary" type="submit" value="Добавить"></td>
                        </tr>
                    </table>
                </form:form>
            </center>
        </div>
    </body>
</html>
...
Рейтинг: 0 / 0
Добавить студента без аватарки
    #39819099
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Сделайте параметр необязательным и будет вам счастье!
@RequestParam( value = "avatar", required = false ) MultipartFile file

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
    @PostMapping(value = "/addStudent")
    public String saveNewStudent(@RequestParam("name") String name,
            @RequestParam("surname") String surname,

            @RequestParam(value = "avatar", required = false) MultipartFile file)


            throws IOException {

        if (file != null && !file.isEmpty()) {
            Student student = new Student();
            student.setSurname(surname);
            student.setName(name);
            student.setAvatar(studentService.saveAvatarImage(file).getName());
            studentService.saveStudent(student);
        }
        return "redirect:/allStudents";
    }
...
Рейтинг: 0 / 0
Добавить студента без аватарки
    #39819100
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Ну и в код тоже внесите соответствующие изменения.
А то напишете "Я скопировал ваш код, но он не работает" :)
...
Рейтинг: 0 / 0
Добавить студента без аватарки
    #39819105
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SQL2008,

Нет я сам код свой написал, просто не могу понять как можно реализовать так чтобы можно было добавлять без аватарки.

Проблема здесь можете помочь
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
 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;
...
Рейтинг: 0 / 0
Добавить студента без аватарки
    #39819111
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
fallen2019, а в чем проблема-то? Ну не вызывайте эту функцию если нет аватарки!
...
Рейтинг: 0 / 0
Добавить студента без аватарки
    #39819159
Фотография Пылинка
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Может, наконец-то, для студенческих курсовых и пр. сделают отдельный форум? А тем более - для их онлайн отладки.
Сюда стало неприятно заходить.
...
Рейтинг: 0 / 0
Добавить студента без аватарки
    #39819179
Фотография Hett
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
ПылинкаМожет, наконец-то, для студенческих курсовых и пр. сделают отдельный форум? А тем более - для их онлайн отладки.
Сюда стало неприятно заходить.

Такой раздел есть, называется "Работа" =)
...
Рейтинг: 0 / 0
Добавить студента без аватарки
    #39819217
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SQL2008,

решил проблему, правда теперь хочу чтобы во время редактирования тоже можно было добавлять фотку по желанию
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
@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";
    }
...
Рейтинг: 0 / 0
Добавить студента без аватарки
    #39820140
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
fallen2019SQL2008,

... теперь хочу чтобы во время редактирования тоже можно было добавлять фотку по желанию
Сейчас матом начну ругаться!
Так добавляйте!
Если вам требуется моё разрешение, то считайте, что я разрешил!
...
Рейтинг: 0 / 0
Добавить студента без аватарки
    #39820142
fallen2019
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
SQL2008,

Я добавил уже просто написал)
...
Рейтинг: 0 / 0
Добавить студента без аватарки
    #39820149
Фотография SQL2008
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
fallen2019SQL2008,

Я добавил уже просто написал)
Ну хорошо... Видимо я не так понял.
Удачи!
...
Рейтинг: 0 / 0
11 сообщений из 11, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Добавить студента без аватарки
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]