We now transition to advanced Servlet operations, handling binary file uploads, database-driven exams, and high-performance non-blocking I/O.
3.1. File Upload & Download Services
Definition: Receives files from clients using multipart forms, and streams binary files back to browsers.
Core Working Principles:
- Multipart forms: Forms must use
enctype="multipart/form-data"to send binary files. - @MultipartConfig: The servlet annotation required to enable file uploads, allowing the use of
request.getPart(). - File Download Headers: Setting the
Content-Dispositionheader to force a browser download dialog.
// Upload file in post
Part filePart = request.getPart("file");
filePart.write("C:/Uploads/" + filePart.getSubmittedFileName());
5-Marks Exam Scoring Points
- request.getPart() retrieves uploaded file parts.
- The Part interface provides utility methods like write() and getSubmittedFileName().
- Binary downloads use application/octet-stream content type.
- Use Content-Disposition header: attachment; filename="...".
3.2. Servlet 3.1 Non-Blocking Read Operations
Definition: Processes requests asynchronously using listeners to prevent thread blocking during large file uploads.
Core Working Principles:
- Asynchronous request processing: Start asynchronous request processing using
request.startAsync(). - ReadListener: Register a
ReadListenerto release the servlet worker thread immediately. - onDataAvailable(): The container triggers event callbacks when data packets arrive.
5-Marks Exam Scoring Points
- asyncSupported=true annotation property is mandatory.
- ReadListener callbacks release server threads, preventing thread pool exhaustion.
- onDataAvailable() processes incoming data packets asynchronously.
- onAllDataRead() executes once the upload is complete, finishing the response.