All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.rongaru.javaee.webapp.servlet.AbstractFileServlet Maven / Gradle / Ivy

package io.github.rongaru.javaee.webapp.servlet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

public abstract class AbstractFileServlet extends HttpServlet {

	protected abstract byte[] getInputStreamBuffer( );

	protected abstract String getSourceFilePath( HttpServletRequest request, HttpServletResponse response );

	@Override
	public String getServletInfo( ) {
		return "This Servlet Allows To Access File System";
	}

	@Override
	protected void doGet( HttpServletRequest request, HttpServletResponse response ) {
		writeFileIntoResponseOutputStream( request, response );
	}

	@Override
	protected void doPost( HttpServletRequest request, HttpServletResponse response ) {
		response.setContentType( "text/html;charset=UTF-8" );
		writeFileIntoResponseOutputStream( request, response );
	}

	protected void writeFileIntoResponseOutputStream( HttpServletRequest request, HttpServletResponse response ) {
		int read = 0;
		byte[] buffer = getInputStreamBuffer( );
		String sourceFilePath = getSourceFilePath( request, response );
		try ( OutputStream outputStream = response.getOutputStream( ) ) {
			try ( InputStream inputStream = new FileInputStream( sourceFilePath ) ) {
				while ( read != -1 ) {
					read = inputStream.read( buffer, 0, buffer.length );
					outputStream.write( buffer, 0, read < 0 ? 0 : read );
				}
			}
		} catch ( Exception e ) {
			e.printStackTrace( );
		}
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy