Issue
So I'm fighting with this issue for 2 hours straight and I cannot find a solution. I have 2 files. Manage.jsp where I'm printing out whole table with data and there I have 2 submit buttons - 1 to delete specific row, other to download a file from within that row.
Submit buttons pass a string regarding to a specific row with a unique name that allows to identify whole row which will be deleted/downloaded within a servlet file.
Similar method works with inserting or other queries but for this one it doesn't seem to work. It is strange especially because same command in MySQL Workbench actually does the job.
@WebServlet("/ManageFiles")
public class ManageFiles extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String alert = "";
String remove = request.getParameter("remove");
String download = request.getParameter("download");
Connection con = null;
if (remove != null) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String DB_NAME = "wap_dama";
out.println("test");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + DB_NAME + "?serverTimezone=UTC","root","asd123");
PreparedStatement ps = con.prepareStatement("delete from wap_dama.files where FileName = ?");
ps.setString(1, remove);
int row = ps.executeUpdate();
if (row > 0)
{
out.println(row);
alert = "Your file was successfully deleted!";
}
}
catch(Exception e) {
e.printStackTrace();
}
}
As for the jsp code
<tbody>
<%
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
String DB_NAME = "wap_dama";
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + DB_NAME + "?serverTimezone=UTC","root","asd123");
PreparedStatement ps = con.prepareStatement("SELECT id_files, FileName, FileExtension, FileSize FROM files WHERE users_id_users=?");
int id = (int) session.getAttribute("id");
ps.setInt(1, id);
ResultSet rs =ps.executeQuery();
//Statement stmt=con.createStatement();
//ResultSet rs=stmt.executeQuery(ps);
while(rs.next())
{
%>
<tr>
<td><%out.println(rs.getString("FileName")); %></td>
<td><%out.println(rs.getString("FileExtension")); %></td>
<td><%out.println(rs.getInt("FileSize")); %></td>
<td><button type="submit" class="btn btn-warning" name="download" value="<%out.println(rs.getString("FileName")); %>">Download</button></td>
<td><button type="submit" class="btn btn-danger" name="remove" value="<%out.println(rs.getString("FileName")); %>">Remove</button></td>
</tr>
<%
}
%>
</tbody>
Any thoughts?
Solution
Okay, seems like the problem has been fixed by simply using .strip()
function next to variable containing name of the file. For some reason there must have been some additional white spaces added and therefore resulting in error.
Answered By - janki3l
Answer Checked By - Cary Denson (JavaFixing Admin)