Serve Image from Servlet Example..

.. nothing special really!

Directory Layout

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/maven-v4_0_0.xsd">
 
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>biz.tugay</groupId>
    <artifactId>bare-webapp</artifactId>
    <packaging>war</packaging>
 
    <version>1.0-SNAPSHOT</version>
 
    <name>bare-webapp</name>
    <url>http://www.tugay.biz</url>
 
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>javax.servlet.jsp.jstl-api</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>3.0.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
 
    <build>
        <finalName>bare-webapp</finalName>
        <plugins>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.2.1.v20140609</version>
            </plugin>
        </plugins>
    </build>
 
    <properties>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
</web-app>

index.jsp
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Bare WebApp</title>
</head>
<body>
<div>
    <h1>${requestScope.helloMessage}</h1>
    <div>
        <img src="images/sample.jpg"
             width="600px"
             alt="Twins with mother"/>
    </div>
</div>
</body>
</html>

WebConstants.java
package biz.tugay.web;
 
import java.io.File;
 
/**
 * User: Koray Tugay (koray@tugay.biz)
 * Date: 21/10/2017
 */
public class WebConstants {
 
    public static final String IMAGES_ROOT_FOLDER_PATH = File.separator +  "images" + File.separator;
}

IndexServlet.java
package biz.tugay.web.servlet;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
 
/**
 * User: Koray Tugay (koray@tugay.biz)
 * Date: 21/10/2017
 */
 
@WebServlet(urlPatterns = "/")
public class IndexServlet extends HttpServlet {
    @Override
    protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) 
        throws ServletException, IOException {
        req.setAttribute("helloMessage", "Hello World!");
        req.getRequestDispatcher("/WEB-INF/pages/index.jsp").forward(req, resp);
    }
}

ImagesServlet.java
package biz.tugay.web.servlet;
 
import biz.tugay.web.WebConstants;
 
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
 
/**
 * User: Koray Tugay (koray@tugay.biz)
 * Date: 21/10/2017
 */
 
// See: http://balusc.omnifaces.org/2007/04/imageservlet.html
@WebServlet(urlPatterns = "/images/*")
public class ImagesServlet extends HttpServlet {
 
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
        final String pathInfo = request.getPathInfo();
        final URL resource = 
            getClass().getClassLoader().getResource(WebConstants.IMAGES_ROOT_FOLDER_PATH + pathInfo);
 
        if (resource == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
            return;
        }
 
        final File image = new File(resource.getFile());
        String contentType = getServletContext().getMimeType(image.getName());
 
        response.reset();
        response.setContentType(contentType);
        response.setHeader("Content-Length", String.valueOf(image.length()));
 
        final Path source = image.toPath();
        final ServletOutputStream outputStream = response.getOutputStream();
        Files.copy(source, outputStream);
    }
}

Build
MacBook-Pro:bare-webapp koraytugay$ mvn clean install
[INFO] Scanning for projects...
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] Building bare-webapp 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ bare-webapp ---
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ bare-webapp ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ bare-webapp ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 3 source files to /Users/koraytugay/bare-webapp/target/classes
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ bare-webapp ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/koraytugay/bare-webapp/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ bare-webapp ---
[INFO] No sources to compile
[INFO] 
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ bare-webapp ---
[INFO] No tests to run.
[INFO] 
[INFO] --- maven-war-plugin:2.2:war (default-war) @ bare-webapp ---
[INFO] Packaging webapp
[INFO] Assembling webapp [bare-webapp] in [/Users/koraytugay/bare-webapp/target/bare-webapp]
[INFO] Processing war project
[INFO] Copying webapp resources [/Users/koraytugay/bare-webapp/src/main/webapp]
[INFO] Webapp assembled in [40 msecs]
[INFO] Building war: /Users/koraytugay/bare-webapp/target/bare-webapp.war
[INFO] WEB-INF/web.xml already added, skipping
[INFO] 
[INFO] --- maven-install-plugin:2.4:install (default-install) @ bare-webapp ---
[INFO] Installing /Users/koraytugay/bare-webapp/target/bare-webapp.war to /Users/koraytugay/DevTools/apache-maven-3.5.0-repo/biz/tugay/bare-webapp/1.0-SNAPSHOT/bare-webapp-1.0-SNAPSHOT.war
[INFO] Installing /Users/koraytugay/bare-webapp/pom.xml to /Users/koraytugay/DevTools/apache-maven-3.5.0-repo/biz/tugay/bare-webapp/1.0-SNAPSHOT/bare-webapp-1.0-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.113 s
[INFO] Finished at: 2017-10-21T16:39:20+02:00
[INFO] Final Memory: 13M/245M
[INFO] ------------------------------------------------------------------------

Lets see what the .war files structure looks like..


Run
MacBook-Pro:bare-webapp koraytugay$ mvn jetty:start
[INFO] Scanning for projects...
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] Building bare-webapp 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] >>> jetty-maven-plugin:9.2.1.v20140609:start (default-cli) > validate @ bare-webapp >>>
[INFO] 
[INFO] <<< jetty-maven-plugin:9.2.1.v20140609:start (default-cli) < validate @ bare-webapp <<<
[INFO] 
[INFO] 
[INFO] --- jetty-maven-plugin:9.2.1.v20140609:start (default-cli) @ bare-webapp ---
[INFO] Logging initialized @1926ms
[INFO] Configuring Jetty for project: bare-webapp
[INFO] webAppSourceDirectory not set. Trying src/main/webapp
[INFO] Reload Mechanic: automatic
[INFO] Classes = /Users/koraytugay/bare-webapp/target/classes
[INFO] Context path = /
[INFO] Tmp directory = /Users/koraytugay/bare-webapp/target/tmp
[INFO] Web defaults = org/eclipse/jetty/webapp/webdefault.xml
[INFO] Web overrides =  none
[INFO] web.xml file = file:/Users/koraytugay/bare-webapp/src/main/webapp/WEB-INF/web.xml
[INFO] Webapp directory = /Users/koraytugay/bare-webapp/src/main/webapp
[INFO] jetty-9.2.1.v20140609
[INFO] Warning: No org.apache.tomcat.JarScanner set in ServletContext. Falling back to default JarScanner implementation.
[INFO] Started o.e.j.m.p.JettyWebAppContext@62482510{/,file:/Users/koraytugay/bare-webapp/src/main/webapp/,AVAILABLE}{file:/Users/koraytugay/bare-webapp/src/main/webapp/}
[WARNING] !RequestLog
[INFO] Started ServerConnector@65869549{HTTP/1.1}{0.0.0.0:8080}
[INFO] Started @2459ms
[INFO] Started Jetty Server

MacBook-Pro:bare-webapp koraytugay$ mvn jetty:start
[INFO] Scanning for projects...
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] Building bare-webapp 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] >>> jetty-maven-plugin:9.2.1.v20140609:start (default-cli) > validate @ bare-webapp >>>
[INFO] 
[INFO] <<< jetty-maven-plugin:9.2.1.v20140609:start (default-cli) < validate @ bare-webapp <<<
[INFO] 
[INFO] 
[INFO] --- jetty-maven-plugin:9.2.1.v20140609:start (default-cli) @ bare-webapp ---
[INFO] Logging initialized @1926ms
[INFO] Configuring Jetty for project: bare-webapp
[INFO] webAppSourceDirectory not set. Trying src/main/webapp
[INFO] Reload Mechanic: automatic
[INFO] Classes = /Users/koraytugay/bare-webapp/target/classes
[INFO] Context path = /
[INFO] Tmp directory = /Users/koraytugay/bare-webapp/target/tmp
[INFO] Web defaults = org/eclipse/jetty/webapp/webdefault.xml
[INFO] Web overrides =  none
[INFO] web.xml file = file:/Users/koraytugay/bare-webapp/src/main/webapp/WEB-INF/web.xml
[INFO] Webapp directory = /Users/koraytugay/bare-webapp/src/main/webapp
[INFO] jetty-9.2.1.v20140609
[INFO] Warning: No org.apache.tomcat.JarScanner set in ServletContext. Falling back to default JarScanner implementation.
[INFO] Started o.e.j.m.p.JettyWebAppContext@62482510{/,file:/Users/koraytugay/bare-webapp/src/main/webapp/,AVAILABLE}{file:/Users/koraytugay/bare-webapp/src/main/webapp/}
[WARNING] !RequestLog
[INFO] Started ServerConnector@65869549{HTTP/1.1}{0.0.0.0:8080}
[INFO] Started @2459ms
[INFO] Started Jetty Server

See In Action