如何在嵌入式码头中添加mime类型

时间:2019-01-09 18:22:54

标签: java jetty mime-types embedded-jetty jetty-9

我正在尝试添加自定义的mime类型:

ServletContextHandler servletHandler
    = new ServletContextHandler(ServletContextHandler.SESSIONS);
MimeTypes mimeTypes = new MimeTypes();
mimeTypes.addMimeMapping("amr", "audio/AMR");
servletHandler.setMimeTypes(mimeTypes);

,但仍然提供不带Content-type标头的amr文件。 这是实际的代码:

package org.traccar.web;

import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.proxy.AsyncProxyServlet;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.webapp.AbstractConfiguration;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.traccar.Config;
import org.traccar.api.AsyncSocketServlet;
import org.traccar.api.CorsResponseFilter;
import org.traccar.api.MediaFilter;
import org.traccar.api.ObjectMapperProvider;
import org.traccar.api.ResourceErrorHandler;
import org.traccar.api.SecurityRequestFilter;
import org.traccar.api.resource.ServerResource;

import javax.servlet.DispatcherType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.net.InetSocketAddress;
import java.util.EnumSet;
import java.util.Set;

public class WebServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebServer.class);

    private Server server;

    private void initServer(Config config) {

        String address = config.getString("web.address");
        int port = config.getInteger("web.port", 8082);
        if (address == null) {
            server = new Server(port);
        } else {
            server = new Server(new InetSocketAddress(address, port));
        }
    }

    public WebServer(Config config) {

        initServer(config);

        ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);

        int sessionTimeout = config.getInteger("web.sessionTimeout");
        if (sessionTimeout > 0) {
            servletHandler.getSessionHandler().setMaxInactiveInterval(sessionTimeout);
        }

        initApi(config, servletHandler);

        if (config.getBoolean("web.console")) {
            servletHandler.addServlet(new ServletHolder(new ConsoleServlet()), "/console/*");
        }

        initWebApp(config, servletHandler);

        servletHandler.setErrorHandler(new ErrorHandler() {
            @Override
            protected void handleErrorPage(
                    HttpServletRequest request, Writer writer, int code, String message) throws IOException {
                writer.write("<!DOCTYPE<html><head><title>Error</title></head><html><body>"
                        + code + " - " + HttpStatus.getMessage(code) + "</body></html>");
            }
        });

        HandlerList handlers = new HandlerList();
        initClientProxy(config, handlers);
        handlers.addHandler(servletHandler);
//        handlers.addHandler(new DefaultHandler());
        server.setHandler(handlers);
    }

    private void initClientProxy(Config config, HandlerList handlers) {
        int port = config.getInteger("osmand.port");
        if (port != 0) {
            ServletContextHandler servletHandler = new ServletContextHandler() {
                @Override
                public void doScope(
                        String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
                        throws IOException, ServletException {
                    if (target.equals("/") && request.getMethod().equals(HttpMethod.POST.asString())) {
                        super.doScope(target, baseRequest, request, response);
                    }
                }
            };
            ServletHolder servletHolder = new ServletHolder(new AsyncProxyServlet.Transparent());
            servletHolder.setInitParameter("proxyTo", "http://localhost:" + port);
            servletHandler.addServlet(servletHolder, "/");
            handlers.addHandler(servletHandler);
        }
    }

    private void initWebApp(Config config, ServletContextHandler servletHandler) {
        ServletHolder servletHolder = new ServletHolder(DefaultServlet.class);
        servletHolder.setInitParameter("resourceBase", config.getString("web.path"));
        if (config.getBoolean("web.debug")) {
            servletHandler.setWelcomeFiles(new String[] {"debug.html", "index.html"});
        } else {
            String cache = config.getString("web.cacheControl");
            if (cache != null && !cache.isEmpty()) {
                servletHolder.setInitParameter("cacheControl", cache);
            }
            servletHandler.setWelcomeFiles(new String[] {"release.html", "index.html"});
        }
        servletHandler.addServlet(servletHolder, "/*");
    }

    private void initApi(Config config, ServletContextHandler servletHandler) {
        servletHandler.addServlet(new ServletHolder(new AsyncSocketServlet()), "/api/socket");

        if (config.hasKey("media.path")) {
            ServletHolder servletHolder = new ServletHolder(DefaultServlet.class);
            servletHolder.setInitParameter("resourceBase", config.getString("media.path"));
            servletHolder.setInitParameter("dirAllowed", config.getString("media.dirAllowed", "false"));
            servletHolder.setInitParameter("pathInfoOnly", "true");
            servletHandler.addServlet(servletHolder, "/api/media/*");
            servletHandler.addFilter(MediaFilter.class, "/api/media/*", EnumSet.allOf(DispatcherType.class));

//            Set<String> knownMimeTypes = MimeTypes.getKnownMimeTypes();
//            MimeTypes mimeTypes = new MimeTypes();
//            mimeTypes.addMimeMapping("amr", "audio/AMR");
//            servletHandler.setMimeTypes(mimeTypes);

            servletHandler.getMimeTypes().addMimeMapping("amr", "audio/AMR");
        }

        ResourceConfig resourceConfig = new ResourceConfig();
        resourceConfig.registerClasses(JacksonFeature.class, ObjectMapperProvider.class, ResourceErrorHandler.class);
        resourceConfig.registerClasses(SecurityRequestFilter.class, CorsResponseFilter.class);
        resourceConfig.packages(ServerResource.class.getPackage().getName());
        servletHandler.addServlet(new ServletHolder(new ServletContainer(resourceConfig)), "/api/*");

    }

    public void start() {
        try {
            server.start();
        } catch (Exception error) {
            LOGGER.warn("Web server start failed", error);
        }
    }

    public void stop() {
        try {
            server.stop();
        } catch (Exception error) {
            LOGGER.warn("Web server stop failed", error);
        }
    }

}

1 个答案:

答案 0 :(得分:0)

不要替换MimeTypes,请修改现有的。

示例:

package jetty;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.resource.PathResource;

public class MimeTypeCustomDemo {
    public static void main(String[] args) throws Exception {
        Server server = new Server(8080);

        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        Path webRootPath = Paths.get("src","test", "resources", "webroot");
        if(Files.notExists(webRootPath)) {
            throw new FileNotFoundException(webRootPath.toString());
        }
        context.setBaseResource(new PathResource(webRootPath));
        context.getMimeTypes().addMimeMapping("amr", "audio/AMR");

        ServletHolder defHolder = new ServletHolder("default", DefaultServlet.class);
        context.addServlet(defHolder, "/");

        HandlerList handlers = new HandlerList();
        handlers.addHandler(context);
        handlers.addHandler(new DefaultHandler());
        server.setHandler(handlers);

        try {
            server.start();
            testGet(server.getURI().resolve("/example.amr"));
        } finally {
            server.stop();
        }
    }

    private static void testGet(URI uri) throws IOException {
        HttpURLConnection http = (HttpURLConnection) uri.toURL().openConnection();
        dumpRequestResponse(http);
    }

    private static void dumpRequestResponse(HttpURLConnection http) throws IOException
    {
        System.out.println();
        System.out.println("----");
        System.out.printf("%s %s HTTP/1.1%n", http.getRequestMethod(), http.getURL());
        System.out.println("----");
        System.out.printf("%s%n", http.getHeaderField(null));
        http.getHeaderFields().entrySet().stream()
                .filter(entry -> entry.getKey() != null)
                .forEach((entry) -> System.out.printf("%s: %s%n", entry.getKey(), http.getHeaderField(entry.getKey())));
    }
}

这导致...

2019-01-09 13:20:10.178:INFO::main: Logging initialized @167ms to org.eclipse.jetty.util.log.StdErrLog
2019-01-09 13:20:10.277:INFO:oejs.Server:main: jetty-9.4.12.v20180830; built: 2018-08-30T13:59:14.071Z; git: 27208684755d94a92186989f695db2d7b21ebc51; jvm 1.8.0_192-b12
2019-01-09 13:20:10.293:INFO:oejsh.ContextHandler:main: Started o.e.j.s.ServletContextHandler@614c5515{/,file:///home/joakim/code/jetty-demos/src/test/resources/webroot/,AVAILABLE}
2019-01-09 13:20:10.305:INFO:oejs.AbstractConnector:main: Started ServerConnector@61dc03ce{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
2019-01-09 13:20:10.306:INFO:oejs.Server:main: Started @296ms

----
GET http://127.0.1.1:8080/example.amr HTTP/1.1
----
HTTP/1.1 200 OK
Accept-Ranges: bytes
Server: Jetty(9.4.12.v20180830)
Last-Modified: Wed, 09 Jan 2019 19:19:50 GMT
Content-Length: 200222
Date: Wed, 09 Jan 2019 19:20:10 GMT
Content-Type: audio/amr
2019-01-09 13:20:10.390:INFO:oejs.AbstractConnector:main: Stopped ServerConnector@61dc03ce{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
2019-01-09 13:20:10.392:INFO:oejsh.ContextHandler:main: Stopped o.e.j.s.ServletContextHandler@614c5515{/,file:///home/joakim/code/jetty-demos/src/test/resources/webroot/,UNAVAILABLE}