Nupur Jaiswal Nupur Jaiswal - 6 months ago 14
Java Question

How to extract row value by using Servlet and JSP?

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 the filename. My program is as follow(JSP file):

<form method="post" action='FileDisplayURL' >
<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" name="filename"></td>
<%
}
%>
</tr>
<%
}
%>
</table>

</form>


This is my servlet:

@WebServlet("/FileDisplayURL")
public class FileDisplay extends HttpServlet {
private static final long serialVersionUID = 1L;

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 how my front page looks like :

enter image description here

I am having a problem in getting the name of file when user clicks for delete.

When I run my program on tomcat, the output in terminal looks like this:

INFO: Server startup in 1076 ms
you clicked on delete


"You clicked on delete" doesn't display the name of the file which is clicked. I am very new to Servlet and JSP. I might be missing something obvious. Any help would be appreciated.

Answer

It's an HTML error, a button can not have value (and you are not adding a value anyway) you should create a hidden input and put the filename there:

<input type="hidden" value="<%=listOfFiles[i].getName()%>" name="filename"/>

Edit:

I did not realize that you have one form, you need a separate form for each row, since the servlet does not know what value put if several inputs have the same name. So your view should have:

<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>
            <form method="post" action='FileDisplayURL' >
                <input type="submit" value="delete">
                <input type="hidden" value="<%=listOfFiles[i].getName()%>" name="filename"/>
            </form>
        </td>
        <%
          }
        %>
    </tr>
    <%
      }
    %>
</table>