How do I handle file uploads using Jakarta Servlet 6.0+?

In Jakarta Servlet 6.0+, file uploads can be handled efficiently using the native APIs provided by the servlet specifications. Here’s a step-by-step guide:

1. Enable Multipart Config for the Servlet

To handle file uploads, the servlet must be annotated with @MultipartConfig, which enables support for handling multipart/form-data requests. You can configure parameters such as maximum file size, total request size, and file location.

Example:

package org.kodejava.servlet;

import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.File;
import java.io.IOException;

@WebServlet("/upload")
@MultipartConfig(
    fileSizeThreshold = 1024 * 1024 * 2, // 2MB. Files above this size will be written to disk.
    maxFileSize = 1024 * 1024 * 10,      // 10MB. Maximum size for a single uploaded file.
    maxRequestSize = 1024 * 1024 * 50,   // 50MB. Maximum size of the entire request.
    location = "/tmp"                    // Temporary directory for uploaded files.
)
public class FileUploadServlet extends HttpServlet {

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

        // Ensure the request is indeed a multipart request
        if (!request.getContentType().startsWith("multipart/form-data")) {
            response.getWriter().println("Invalid request type");
            return;
        }

        // Retrieve the part associated with the upload form field
        Part filePart = request.getPart("file");  // "file" is the form field name
        if (filePart != null) {
            // Retrieve file information
            String fileName = extractFileName(filePart);
            long fileSize = filePart.getSize(); // Size of the file in bytes

            // Define file path for saving
            String uploadDir = getServletContext().getRealPath("") + File.separator + "uploads";
            File uploadDirFile = new File(uploadDir);
            if (!uploadDirFile.exists()) {
                uploadDirFile.mkdirs(); // Create directories if they don't exist
            }
            String filePath = uploadDir + File.separator + fileName;

            // Write the uploaded file to the target directory
            filePart.write(filePath);

            // Respond back to the client
            response.getWriter().println("File uploaded successfully to: " + filePath);
        } else {
            response.getWriter().println("File upload failed. Missing file part.");
        }
    }

    // Utility method to extract the file name from the HTTP header
    private String extractFileName(Part part) {
        String contentDisposition = part.getHeader("content-disposition");
        for (String content : contentDisposition.split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(content.indexOf("=") + 2, content.length() - 1); // Extract filename
            }
        }
        return "unknown";
    }
}

2. Create a Front-End Form

Ensure your front-end has a form with the enctype="multipart/form-data" attribute.

Example HTML Form:

<!DOCTYPE html>
<html>
<head>
    <title>File Upload</title>
</head>
<body>
    <h2>Upload a File</h2>
    <form method="post" action="/upload" enctype="multipart/form-data">
        <label for="file">Choose a file:</label>
        <input type="file" name="file" id="file" required>
        <br>
        <button type="submit">Upload</button>
    </form>
</body>
</html>

3. Explanation of Key Parts in the Code

  • @MultipartConfig Annotation:
    • fileSizeThreshold: Files larger than this threshold are written to disk instead of memory.
    • maxFileSize: The maximum size allowed for a single file.
    • maxRequestSize: The maximum size allowed for the entire request (including all parts).
    • location: Directory where files are stored temporarily. Files exceeding the threshold are saved here.
  • Part Object:
    • Represents a part in a multipart request. You can use it to get the file content, headers, and write it to a file.
  • extractFileName() Utility Function:
    • Extracts the file name from the content-disposition header of the Part.

4. File Storage Directory

Ensure the target directory exists (or is created) where the uploaded files will be stored. The example uses a directory inside your web application (uploads folder).
For production setups, consider storing files in external directories to avoid packaging issues.

5. Additional Considerations

  • Validation:
    • Validate the uploaded file (e.g., file type, size) for security reasons.
  • Error Handling:
    • Use appropriate exception handling for cases like large files (IllegalStateException) or I/O errors.
  • Security:
    • Always sanitize the file name and restrict file types to prevent malicious uploads.

6. Dependencies

If you’re using a Jakarta Servlet container (e.g., Apache Tomcat 10+), make sure the servlet API dependency exists in your pom.xml (or equivalent build file):

With this setup, your servlet will successfully handle file uploads in Jakarta Servlet 6.0+! Let me know if you have further questions or need additional details

Maven dependencies

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.1.0</version>
    <scope>provided</scope>
</dependency>

Maven Central

How do I serve static files through a Jakarta Servlet?

To serve static files (e.g., HTML, CSS, JavaScript, images) using a Jakarta Servlet, you can follow these steps. Jakarta Servlets provide a way to read files from a directory (or resources) and serve them as HTTP responses.

Here’s a guide on how to achieve it:

1. Directory Structure

Your project structure should look something like this:

src/main/resources/static/
    ├── index.html
    ├── styles.css
    ├── script.js
    └── images/
        └── logo.png

All the static files (HTML, CSS, JavaScript, images, etc.) should be placed in a directory (e.g., static) within your resources or web-app deployment directory.

2. Servlet Implementation

Create a custom Servlet to handle requests for static files. The servlet will read files from the static folder and write the content to the HTTP response.
Here’s an example:

package org.kodejava.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLConnection;

@WebServlet("/static/*")
public class StaticFileServlet extends HttpServlet {

    private static final String STATIC_DIR = "/static/"; // Path to static files directory

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Get the requested file path from the URL
        String requestedFile = req.getPathInfo();

        if (requestedFile == null || requestedFile.equals("/")) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "File name is missing");
            return;
        }

        // Locate the static file
        File file = new File(getServletContext().getRealPath(STATIC_DIR + requestedFile));

        // Ensure the file exists and is not a directory
        if (!file.exists() || file.isDirectory()) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
            return;
        }

        // Set the content type based on the file type
        String mimeType = URLConnection.guessContentTypeFromName(file.getName());
        if (mimeType == null) {
            mimeType = "application/octet-stream"; // Default binary type
        }
        resp.setContentType(mimeType);

        // Write the file content to the response
        try (FileInputStream fis = new FileInputStream(file);
             OutputStream os = resp.getOutputStream()) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        }
    }
}

3. Explanation of the Code

  • Annotation:
    • The @WebServlet("/static/*") annotation maps all requests starting with /static/ to this servlet.
  • Requested Path:
    • req.getPathInfo() retrieves the path of the resource the user requested (/static/styles.css becomes /styles.css).
  • File Retrieval:
    • The static directory location is derived using getServletContext().getRealPath().
  • MIME Type:
    • URLConnection.guessContentTypeFromName() determines the file type so the browser knows how to handle the response.
  • File Output:
    • The file is read using an input stream and written to the output stream of the HTTP response in chunks.

4. Web Deployment Descriptor (Optional Alternative)

If you’re not using annotations, you can register the servlet in the WEB-INF/web.xml file as follows:

<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         version="10.0">
    <servlet>
        <servlet-name>StaticFileServlet</servlet-name>
        <servlet-class>org.kodejava.servlet.StaticFileServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>StaticFileServlet</servlet-name>
        <url-pattern>/static/*</url-pattern>
    </servlet-mapping>
</web-app>

5. Test the Static File Server

Place some static files (e.g., index.html, styles.css) in your static directory. Start your server and access them via URLs like:

  • http://localhost:8080/static/index.html
  • http://localhost:8080/static/styles.css

6. Additional Considerations

  1. Security:
    • Be cautious about serving sensitive files. Use checks to block access to directories outside your static folder.
  2. Caching:
    • Consider adding HTTP headers for caching, such as Cache-Control or ETag.
  3. Alternative: Use Jakarta Servlet DefaultServlet:
    • Many Jakarta Servlet containers (e.g., Tomcat) have a DefaultServlet for serving static resources without custom code. You can configure it with <servlet> and <servlet-mapping> in web.xml.

Here’s a simple example:

<servlet>
    <servlet-name>default</servlet-name>
    <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
    <init-param>
        <param-name>listings</param-name>
        <param-value>false</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/static/*</url-pattern>
</servlet-mapping>

If you configure this, files from /static/ will be served directly without writing a custom servlet.

Maven dependencies

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.1.0</version>
    <scope>provided</scope>
</dependency>

Maven Central

How do I use annotations to define Jakarta Servlet?

In Jakarta EE, you can define servlets using annotations instead of the traditional web.xml deployment descriptor. The most common annotation used for this purpose is @WebServlet. Here’s an overview of how to use annotations to define servlets:

1. Basic Syntax of the @WebServlet Annotation

The @WebServlet annotation is used to declare a servlet and map it to a URL pattern. It belongs to the jakarta.servlet.annotation package.

package org.kodejava.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "MyServlet", urlPatterns = {"/hello", "/greet"})
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        response.getWriter().println("<h1>Hello, World!</h1>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        response.getWriter().println("<h1>Post Request Handled</h1>");
    }
}

2. Parameters of @WebServlet

The @WebServlet annotation has several attributes you can set:

  1. name: Specifies the name of the servlet. This is optional.
  2. urlPatterns (or value): An array of URL patterns to which the servlet will respond. The urlPatterns or value element is required.
  3. loadOnStartup: Specifies the servlet’s load-on-startup priority. If set to a positive integer, the servlet will be loaded and initialized during deployment, not upon its first request.
  4. asyncSupported: A boolean indicating whether the servlet supports asynchronous processing. Default is false.

Example with Additional Attributes

package org.kodejava.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet(
        name = "ExampleServlet",
        urlPatterns = "/example",
        loadOnStartup = 1,
        asyncSupported = true
)
public class ExampleServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/plain");
        response.getWriter().println("Welcome to the Example Servlet!");
    }
}

3. How It Works

  • No web.xml Needed: When you use @WebServlet, there’s no need to register the servlet manually in web.xml. The application server automatically registers the servlet based on the annotation configuration.
  • URL Patterns: You define the URLs (using urlPatterns or value) to which the servlet will respond.

4. Multiple URL Patterns

You can map multiple URL patterns to the same servlet using an array:

package org.kodejava.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet(urlPatterns = {"/path1", "/path2", "/path3"})
public class MultiPathServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/plain");
        response.getWriter().println("This servlet can handle multiple paths!");
    }
}

5. Use with Filters and Listeners

Annotations can also be used for filters (@WebFilter) and listeners (@WebListener). For example:

  • @WebFilter for filters
  • @WebListener for event listeners

Conclusion

Using annotations to define servlets makes your code more concise and simplifies configuration. It eliminates the need for verbose web.xml entries and is easier to maintain, particularly in modern Jakarta EE-based applications.


Maven dependencies

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.1.0</version>
    <scope>provided</scope>
</dependency>

Maven Central

How do I configure servlets in web.xml?

In a Jakarta EE (formerly Java EE) application, you can configure servlets in the web.xml deployment descriptor. The web.xml file is located in the WEB-INF directory of your project. Here’s how you can configure a servlet in web.xml step-by-step:

1. Declare the Servlet

You define the servlet by giving it a name and specifying its implementing class.

<servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>org.kodejava.servlet.MyServlet</servlet-class>
</servlet>

2. Map the Servlet to a URL Pattern

After declaring the servlet, you specify the URL patterns (endpoints) it should handle.

<servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/myServlet</url-pattern>
</servlet-mapping>

The servlet-name in the <servlet-mapping> must match the one defined in the <servlet> section.

Complete Example

Below is a complete example of web.xml configuration for a servlet:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
         version="6.0">

    <!-- Declare the servlet -->
    <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>org.kodejava.servlet.MyServlet</servlet-class>
    </servlet>

    <!-- Map the servlet to a URL pattern -->
    <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/myServlet</url-pattern>
    </servlet-mapping>

</web-app>

Understanding the Tags

  • <servlet>: Declares the servlet, including its name and fully qualified class name.
  • <servlet-name>: A unique name for your servlet (used in <servlet-mapping> to link configuration).
  • <servlet-class>: The fully qualified class name of the servlet (e.g., org.kodejava.servlet.MyServlet).
  • <servlet-mapping>: Maps the declared servlet to specific URL patterns (e.g., /myServlet).
  • <url-pattern>: Specifies the URL or set of URLs that the servlet will handle.

Notes:

  1. URL Patterns:
    • /myServlet matches a specific path.
    • /* matches all paths.
    • /example/* matches all paths under /example.
  2. Multiple Servlet Mappings: You can map the same servlet to multiple URL patterns by adding multiple <servlet-mapping> entries.

  3. Override Annotations: If you use @WebServlet annotations in your servlet class, you generally won’t need to configure the servlet in web.xml. However, web.xml still allows more control over deployment and compatibility with older specifications.
  4. Jakarta EE Web.xml Version:
    The <web-app> version should match the Jakarta EE version you are using. For Jakarta EE 10, use version="6.0" as shown above.

How do I include content from another servlet or JSP?

To include the content of one servlet or JSP into another, you can use the functionality provided by the RequestDispatcher interface in Jakarta Servlet (previously Javax Servlet). The two primary methods for including content are:

  1. Using RequestDispatcher.include():
    This method includes the response of another servlet or JSP within the response of the current servlet or JSP.

  2. Using <jsp:include /> Tag:
    This is specifically used in JSP to include another JSP or servlet dynamically.


1. Using RequestDispatcher.include() in servlets

You can use the include() method of the RequestDispatcher to include the content of another servlet or JSP. Here’s how it works:

  • Steps:
    1. Obtain a RequestDispatcher object for the target servlet or JSP.
    2. Use the include() method to include its output.

Example Code:

package org.kodejava.servlet;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;

@WebServlet("/include")
public class IncludeServletExample extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        var out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>Content from Main Servlet</h1>");

        // Getting RequestDispatcher for another servlet or JSP
        RequestDispatcher dispatcher = request.getRequestDispatcher("/example");

        // Including content
        dispatcher.include(request, response);

        out.println("<h1>This is after including the content</h1>");
        out.println("</body></html>");
    }
}

2. Using <jsp:include /> in JSP

This is used to include either static or dynamic content from another JSP or servlet directly within a JSP page.

  • Syntax:
<jsp:include page="URL or Path" />

The page attribute specifies the relative URL or path of the servlet or JSP to be included.

Example Code:

<html>
<body>
  <h1>Content from Main JSP</h1>

  <!-- Include another servlet or JSP -->
  <jsp:include page="includedJspPage.jsp" />

  <h1>This is after including the content</h1>
</body>
</html>

Important Notes

  • Differences between include() and forward():
    • include(): Includes the response from the target servlet/JSP into the current response. The execution continues after including the content.
    • forward(): Forwards the request to another servlet/JSP. The control does not return to the original servlet/JSP.
  • Context-relative paths:
    • When specifying the path in RequestDispatcher (e.g., /example), always use context-relative paths (starting with a / relative to the root of the web application).
  • Dynamic Content:
    • The target servlet or JSP can contain dynamic content, as it is executed when included.

Maven dependencies

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.1.0</version>
    <scope>provided</scope>
</dependency>

Maven Central