Nupur Jaiswal Nupur Jaiswal - 6 months ago 8
HTML Question

Delete button in JSP to delete files from server

I am a newbie to JSP. I have created a jsp file which runs on the tomcat server. I have specified my directory location in my program. My program displays all the files from that directory and displays results in a table and creates a delete button after filename. My program is as follow(JSP file):

<%@page import="java.io.File"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Directories</title>
</head>
<body>
<h2>Current Collection</h2>
<table width="100%" border="1">

<%
File folder = new File("C:/Apps/eclipse-jee-mars-2-win32-x86_64/eclipse");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
%>
<tr>
<%
if (listOfFiles[i].isFile()) {
%>
<td><%=listOfFiles[i].getName()%></td>
<td><input type="submit" value="delete"></td>
<%
}
%>
</tr>
<%
}
%>
</table>
</body>
</html>


When I run this on my server, my output looks like this:
http://i.stack.imgur.com/fFgxy.png

When user click on delete button, I want the file to be deleted from my local machine. I am very new to JSP and I am not sure how to do this. Any help would be appreciated. Thank you.

Edit:
This is my servlet:

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");

String deleteFileName = request.getParameter("filename");
System.out.println("you clicked on " + deleteFileName);

}


This is my jsp:

<tr >
<%
if (listOfFiles[i].isFile()) {
%>
<td><%=listOfFiles[i].getName()%></td>
<td><input type="submit" value="delete" name="filename"></td>
<%
}
%>
</tr>

Answer

You need a HTML <form> tag, and specify the action="" attribute as a URL which will then trigger the the Servlet (or JSP) which will receive the HTTP parameters and do the action.

Comments