HttpServletRequest#getPart doesn’t exist?

I have a Java WebApp in which I need to upload a file. According to what I’ve found on the Internet, here’s what I’ve tried:

public class FileUploadController extends HttpServlet {
    private final String UPLOAD_DIRECTORY = "C:/uploads";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Part filePart = request.getPart("file");
    }

However, the IDE complained about an undefined symbol getPart. So I went ahead and found that you need the Servlet API 3.0 at least to get this method, and my project only had Servlet API 2.5. I changed the required version of the API in the pom.xml file from 2.5 to 3.0-alpha-1 (which was proposed by the autocompletion), and clean-built the project.

But I still have this error about getPart not existing. Did I miss something?

Answer

The artifact id was changed to javax.servlet-api somewhere during the development of the 3.0 version of the Servlet API. Version 3.0-alpha-1 is a very early pre-release, which might not yet have the getPart(String) method.

To get the current 3.0.x release of the Servlet API, use the following dependency:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
</dependency>

Leave a Reply

Your email address will not be published. Required fields are marked *