Я написал код который добавляет имя, фамилию студента через сервлет в базу данных MySQL. Теперь же хочу добавить функцию которая позволяет каждому студенту добавлять фото. Я написал код но там ошибка. Как можно исправить В этом месте
stmt.setString(1, name);
stmt.setString(2, surname);
String filePath = savePath + File.separator + fileName; //ЗДЕСЬ
stmt.setString(3, filePath);
stmt.executeUpdate();
ResultSet keys = stmt.getGeneratedKeys();
} catch (SQLException e) {
throw new RuntimeException(e);
}
Мой сервлет
package servlet;
import dao.DatabaseDAO;
import entity.Student;
import java.io.File;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.Integer.parseInt;
import java.util.List;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Part;
@WebServlet("/MyServlet")
@MultipartConfig(fileSizeThreshold = 1024*1024*2,
maxFileSize=1024*1024*10,
maxRequestSize = 1024*1024*50)
public class MyServlet extends HttpServlet {
private DatabaseDAO dao;
private static final String SAVE_DIR = "images";
@Override
public void init() throws ServletException {
dao = new DatabaseDAO();
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String savePath = "C:/Users/Adil/Documents/NetBeansProjects/MySchool/web" + File.separator + SAVE_DIR;
File fileSaveDir = new File(savePath);
String action = request.getParameter("actionname");
if (action.equals("addstudent")) {
String name = request.getParameter("name");
String surname = request.getParameter("surname");
Part part=request.getPart("images");
String fileName=extractFileName(part);
part.write(savePath + File.separator + fileName);
dao.insertStudentIntoDB(name, surname, images);
request.setAttribute("message", "Студент добавлен.");
List<Student> students = dao.readAllStudentsFromDB();
request.setAttribute("students", students);
request.getRequestDispatcher("ShowAllStudent.jsp").forward(request, response);
}
if (action.equals("RemoveStudent")) {
int id = parseInt(request.getParameter("id"));
boolean deleted = dao.deleteStudentFromDB(id);
String message;
if (deleted) {
message = "Студент удален.";
} else {
message = "Студент не существует";
}
request.setAttribute("message", message);
List<Student> students = dao.readAllStudentsFromDB();
request.setAttribute("students", students);
request.getRequestDispatcher("ShowAllStudent.jsp").forward(request, response);
}
if (action.equals("ShowAllStudent")) {
List<Student> students = dao.readAllStudentsFromDB();
request.setAttribute("students", students);
request.getRequestDispatcher("ShowAllStudent.jsp").forward(request, response);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for(String s : items) {
if (s.trim().startsWith("filename")){
return s.substring(s.indexOf("=") + 2, s.length()-1);
}
}
}
}
Класс DAO
package dao;
import entity.Student;
import java.io.File;
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");
Student student = new Student(firstName, lastName);
student.setId(id);
result.add(student);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return result;
}
public void insertStudentIntoDB(String name, String surname, String filePath) {
try (PreparedStatement stmt =
conn.prepareStatement(INSERT_STUDENT_QUERY, Statement.RETURN_GENERATED_KEYS)) {
stmt.setString(1, name);
stmt.setString(2, surname);
String filePath = savePath + File.separator + fileName;
stmt.setString(3, filePath);
stmt.executeUpdate();
ResultSet keys = stmt.getGeneratedKeys();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
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 Add Student
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>fSchool</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="css/addstudent.css">
<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="css/menu.css">
<script src="js/jquery1111.min.js" type="text/javascript"></script>
<script src="js/script.js"></script>
</head>
<body class="home-page">
<div class="wrap-body">
<header>
<div id="cssmenu">
<ul>
<li class="active"><a href="index.html"><span>FSchool</span></a></li>
<li class="has-sub"><a href="#"><span>Students</span></a>
<ul>
<li><a href="./servlet.MyServlet?actionname=ShowAllStudent"><span>Show All Students</span></a>
<li><a href="AddStudent.jsp"><span>Add student</span></a>
<li><a href="RemoveStudent.jsp"><span>Remove Student</span></a>
</li>
</ul>
</li>
<li><a href="archive.html"><span>Media</span></a></li>
<li><a href="single.html"><span>Skills</span></a></li>
<li class="last"><a href="contact.html"><span>About</span></a></li>
</ul>
</div>
</header>
<div class="addstudent">
<h1>Add Student</h1>
<form action="servlet.MyServlet" method="Post">
name : <input type="text" name="name"><br><br>
surname : <input type="text" name="surname"><br><br>
image: <input type="file" name="photo"><br><br>
<input type="hidden" value="addstudent" name="actionname">
<input type="submit" value="Send"><br>
</form>
</div>
</div>
</body>
</html>
Виртуальный выделенный сервер (VDS) становится отличным выбором
Подскажите как запустить этот проект? https://githubcom/CaymanJava/online_banking
Учусь работать с JPAЕсть MySQL таблица с полями a,b,c,d,e
Собственно, в заголовке вопросАннотации JPA привязывают нас к самому JPA