Не показывает фотку в таблице (Servlet)
#39786761
Ссылка:
Ссылка на сообщение:
Ссылка с названием темы:
|
|
|
Я написал программу которая через сервлет добавляет имя, фамилию и фотку студента в БД.
И фотку студента он хранит в жестком диске С в папке Pictures. Но после этого он не показывает фотку студента в таблице
Вот мой код
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.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package servlet;
import dao.DatabaseDAO;
import entity.Student;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
*
* @author Oleksii
*/
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50) // 50MB
public class AddStudentServlet extends HttpServlet {
/**
* Name of the directory where uploaded files will be saved, relative to the
* web application directory.
*/
private static final String SAVE_DIR = "images";
private DatabaseDAO dao;
@Override
public void init() throws ServletException {
dao = new DatabaseDAO();
}
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// gets absolute path of the web application
String appPath = request.getServletContext().getRealPath("");
// creates the save directory if it does not exists
String savePath = "C:\\Pictures";
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdirs();
}
String name = request.getParameter("name");
String surname = request.getParameter("surname");
String fileName;
for (Part part : request.getParts()) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String item : items) {
String ss = item.trim();
if (ss.startsWith("filename")) {
String fileExt = ss.substring(ss.lastIndexOf("."), ss.length() - 1); // расширение включая точку
try {
int id = dao.insertStudentIntoDB(name, surname);
fileName = String.valueOf(id);
System.out.println(savePath + File.separator + fileName + fileExt);
part.write(savePath + File.separator + fileName + fileExt);
request.setAttribute("message", "Студент добавлен.");
} catch (IOException e) {
request.setAttribute("message", "Ошибка при добавлении студента!");
}
}
}
}
List<Student> students = dao.readAllStudentsFromDB();
request.setAttribute("students", students);
request.getRequestDispatcher("ShowAllStudent.jsp").forward(request, response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
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.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package servlet;
import dao.DatabaseDAO;
import entity.Student;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
*
* @author Oleksii
*/
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50) // 50MB
public class AddStudentServlet extends HttpServlet {
/**
* Name of the directory where uploaded files will be saved, relative to the
* web application directory.
*/
private static final String SAVE_DIR = "images";
private DatabaseDAO dao;
@Override
public void init() throws ServletException {
dao = new DatabaseDAO();
}
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// gets absolute path of the web application
String appPath = request.getServletContext().getRealPath("");
// creates the save directory if it does not exists
String savePath = "C:\\Pictures";
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdirs();
}
String name = request.getParameter("name");
String surname = request.getParameter("surname");
String fileName;
for (Part part : request.getParts()) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String item : items) {
String ss = item.trim();
if (ss.startsWith("filename")) {
String fileExt = ss.substring(ss.lastIndexOf("."), ss.length() - 1); // расширение включая точку
try {
int id = dao.insertStudentIntoDB(name, surname);
fileName = String.valueOf(id);
System.out.println(savePath + File.separator + fileName + fileExt);
part.write(savePath + File.separator + fileName + fileExt);
request.setAttribute("message", "Студент добавлен.");
} catch (IOException e) {
request.setAttribute("message", "Ошибка при добавлении студента!");
}
}
}
}
List<Student> students = dao.readAllStudentsFromDB();
request.setAttribute("students", students);
request.getRequestDispatcher("ShowAllStudent.jsp").forward(request, response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
DAO
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.
package dao;
import entity.Student;
import java.sql.*;
import java.time.LocalDate;
import java.util.ArrayList;
public class DatabaseDAO {
private static final String URL = "jdbc:mysql://localhost:3306/school_db_newnew?useTimezone=true&serverTimezone=GMT";
private static final String USER = "root";
private static final String PASSWORD = "123456";
private static final String GET_ALL_STUDENTS_QUERY
= "SELECT * FROM student;";
private static final String INSERT_STUDENT_QUERY
= "INSERT INTO student (name, surname) VALUES(?,?);";
public static final String DELETE_STUDENT_QUERY = "DELETE FROM student WHERE id = ?;";
private Connection conn;
public DatabaseDAO() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public ArrayList<Student> readAllStudentsFromDB() {
ArrayList<Student> result = new ArrayList<>();
try (PreparedStatement stmt = conn.prepareStatement(GET_ALL_STUDENTS_QUERY)) {
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String firstName = rs.getString("name");
String lastName = rs.getString("surname");
String patron = rs.getString("patron");
Date date = rs.getDate("birthday");
LocalDate birthday = null;
if (date != null) {
birthday = date.toLocalDate();
}
String image = rs.getString("image");
Student student = new Student(firstName, lastName, patron, birthday);
student.setId(id);
student.setImage(image);
result.add(student);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return result;
}
public int insertStudentIntoDB(String name, String surname) {
try (PreparedStatement stmt
= conn.prepareStatement(INSERT_STUDENT_QUERY, Statement.RETURN_GENERATED_KEYS)) {
stmt.setString(1, name);
stmt.setString(2, surname);
stmt.executeUpdate();
ResultSet keys = stmt.getGeneratedKeys();
if (keys.next()) {
return keys.getInt(1);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return -1;
}
public boolean deleteStudentFromDB(int id) {
try (PreparedStatement stmt = conn.prepareStatement(DELETE_STUDENT_QUERY)) {
stmt.setInt(1, id);
int rowsDeleted = stmt.executeUpdate();
return rowsDeleted > 0;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
JSP
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.
<div class="addstudent">
<h1>Add Student</h1>
<form action="AddStudent" method="Post" enctype="multipart/form-data">
name : <input type="text" name="name"><br><br>
surname : <input type="text" name="surname"><br><br>
image: <input name="data" type="file" accept="image/*"><br>
<input type="submit" value="Send"><br>
</form>
</div>
</div>
</body>
</html>
|
|