UPDATE
Sorry, I initially missed the enctype="multipart/form-data"
part. So, as the user @tomor correctly noted, the reason behind your problem is that you use enctype="multipart/form-data"
. Read his answer.
For the more detailed explanation of your issue read the following answer by BalusC: How to upload files to server using JSP/Servlet?.
The following solution is for the Servlet v3.0. For the older versions, the most popular solution is using Apache Commons FileUpload (see the details in the BalusC answer).
If you want to check what submit button was pressed, one of the solutions could be naming the submit buttons the same and then checking the values.
Example:
HTML
<form action="FileUpload" method="post" enctype="multipart/form-data">
<input type="file" id="filename" name="filename"><br>
<input type="button" value="Upload"><br>
<input type="submit" value="Generate PDF" name="submitAction">
<input type="submit" value="Generate Excel" name="submitAction">
</form>
Servlet
NB! Pay attention to the @MultipartConfig annotation (available since Servlet 3.0). This way you can correctly process multipart/form-data requests.
TestServlet.java
package com.example;
import javax.servlet.http.HttpServlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
@WebServlet(urlPatterns = {"/TestSubmit.do"})
@MultipartConfig
public class TestServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String submitAction= request.getParameter("submitAction");
if (submitAction != null) {
if (submitAction.equals("Generate PDF")) {
System.out.println("Generate PDF button pressed");
} else if (submitAction.equals("Generate Excel")) {
System.out.println("Generate Excel button pressed");
}
} else {
// do something about it
}
}
}
NOTE:
Instead of @WebServlet
(again since Servlet 3.0) you can, of course, make servlet configurations inside web.xml. Same for the @MultipartConfig
: instead of this annotation you could add the <multipart-config>
as a child element of the servlet configuration element in the web.xml file.
Example (excerpt from web.xml):
<servlet>
<servlet-name>Test Servlet</servlet-name>
<servlet-class>com.example.TestServlet</servlet-class>
<multipart-config>
<!-- In this case empty, but can contain additional nested elements -->
</multipart-config>
</servlet>
<servlet-mapping>
<servlet-name>Test Servlet</servlet-name>
<url-pattern>/TestSubmit.do</url-pattern>
</servlet-mapping>
More useful links: