| 
 29.04.2019, 11:05 
    
           
    
    #39807477
    
    
        Ссылка: 
    
    Ссылка на сообщение: 
    
    Ссылка с названием темы: 
    
    
    
                                                                    
    
     
 
 
 | 
| 
  
 | 
 | 
Nixic, 
 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.
  package adil.java.schoolmaven.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import adil.java.schoolmaven.entity.Student;
import adil.java.schoolmaven.service.StudentService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
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 {
    private final static File UPLOAD_FOLDER = new File(System.getProperty("user.dir") + "/avatars/");
    static {
        if (!UPLOAD_FOLDER.exists()) {
            UPLOAD_FOLDER.mkdirs();
        }
    }
    // 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(HttpServletResponse response) {
        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.setSurname(name);
            student.setAvatar(file.getBytes());
            studentService.saveStudent(student);
        }
        return "redirect:/allStudents";
    }
    @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());
    }
    @RequestMapping(value = "/editStudent/{id}", method = RequestMethod.GET)
    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;
    }
    @RequestMapping(value = "/editStudent/{id}", method = RequestMethod.POST)
    public ModelAndView saveEditedUser(@ModelAttribute Student student, BindingResult result) {
        ModelAndView mv = new ModelAndView("redirect:/allStudents");
        if (result.hasErrors()) {
            System.out.println(result.toString());
            return new ModelAndView("error");
        }
        boolean isSaved = studentService.saveStudent(student);
        if (!isSaved) {
            return new ModelAndView("error");
        }
        return mv;
    }
    @RequestMapping(value = "/deleteStudent/{id}", method = RequestMethod.GET)
    public ModelAndView deleteUserById(@PathVariable Long id) {
        boolean isDeleted = studentService.deleteStudentById(id);
        System.out.println("Удаление студента: " + isDeleted);
        ModelAndView mv = new ModelAndView("redirect:/allStudents");
        return mv;
    }
}
   
 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.
  package adil.java.schoolmaven.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@EnableJpaRepositories
@ComponentScan(basePackages = "adil.java.schoolmaven")
public class WebMvcConfig implements WebMvcConfigurer {
	@Bean
	public ViewResolver getViewResolver() {
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setPrefix("/WEB-INF/views/");
		resolver.setSuffix(".jsp");
		return resolver;
	}
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/resources/**").addResourceLocations("/resources/css");
	}
	@Bean
	public MultipartResolver multipartResolver() {
		return new StandardServletMultipartResolver();
	}
}
	//@Override
	//public void configureViewResolvers(ViewResolverRegistry registry) {
	//	registry.jsp().prefix("/WEB-INF/views/").suffix(".jsp");
	//}
	// @Bean
	// public MessageSource messageSource() {
	// ResourceBundleMessageSource messageSource = new
	// ResourceBundleMessageSource();
	// messageSource.setBasename("messages");
	// return messageSource;
	// }
	
	/*@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/").setViewName("index");
	}*/
   
 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.
  package adil.java.schoolmaven.config;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
	private final int DEFAULT_SIZE = 10 * 1024 * 1024;
	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class[] { HibernateConfig.class };
	}
	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class[] { WebMvcConfig.class };
	}
	@Override
	protected String[] getServletMappings() {
		return new String[] { "/" };
	}
        
        @Override
        protected void customizeRegistration(ServletRegistration.Dynamic registration) {
        registration.setMultipartConfig(new MultipartConfigElement("", DEFAULT_SIZE, DEFAULT_SIZE, DEFAULT_SIZE));
    }
}
   
 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.
  <%@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="/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>
   
 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.
  <%@ 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"%>
<!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="/WEB-INF/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">Имя</th>
     
      <th scope="col">Фамилия</th>
      <th scope="col">Фото</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><img src="data:image/jpg;base64,${student.base64Image}" style="max-height: 200px; max-width: 200px;" /></td>
                    
                     <td><a
                        href="${pageContext.request.contextPath}/editStudent/${student.id}"><button type="button" class="btn btn-primary">Редактировать</button>
                    <td><a
                        href="${pageContext.request.contextPath}/deleteStudent/${student.id}"><button type="button" class="btn btn-primary">Удалить</button>
                            
                           
                            
                </tr>
            </c:forEach>
        </tbody>
    
    </table>
    <a href="${pageContext.request.contextPath}/addStudent"><button type="button" class="btn btn-primary">Добавить студента</button></a>
    </div>
</body>
</html>
  
 | 
| 
 |