Display static HTML file from resources folder in Jetty Serverlet doGet method

时间:2015-12-14 17:55:15

标签: java jetty

I have a servlet which I want to return a resource, or at least the html from the resource, index.html which is located in my webapps folder.

I'm very new and haven't been able to find anything. Here's my code I would appreceiate any help!

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

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setDirectoriesListed(true);
    resource_handler.setWelcomeFiles(new String[]{"index.html"});
    resource_handler.setResourceBase("./target/classes/webapp");

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");

    ServletHolder indexHolder = new ServletHolder(new IndexServlet());
    context.addServlet(indexHolder, "/index");

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[]{resource_handler, context, new DefaultHandler()});
    server.setHandler(handlers);

    try {
        server.start();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

This is my current doGet method. The print staement currently is the string value of the index.html file that I would like the servlet to return.

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

    response.getWriter().print(
            "<!doctype html>\n" +
            "<html>\n" +
            "<head>\n" +
            "<meta charset=\"utf-8\">\n" +
            "<title>Form Page</title>\n" +
            "</head>\n" +
            "<body>\n" +
            "    <form id=\"jetty-form\" name=\"user-form\" method=\"post\">\n" +
            "        <label for=\"username\">Username:</label>\n" +
            "        <input type=\"text\" name=\"username\" id=\"username\">\n" +
                            "<input type=\"submit\">" +
            "    </form>\n" +
            "</body>\n" +
            "</html>");

}

1 个答案:

答案 0 :(得分:2)

Do not use ResourceHandler and ServletContextHandler together。 (先前的答案)

完全删除ResourceHandler。

删除IndexServlet(你不需要它)。

创建src/main/webapp/index.html(如果使用Maven和WAR项目类型)并将HTML写为HTML。

ServletContextHandler需要资源库。

资源库应该是后处理静态内容的完整(绝对)路径(非相对)。如果您的构建版本复制/创建/修改资源,则需要注意这一点并使用备用目录位置。也可以使用jar:file://目录位置。

当您从IDE运行/ debug / test时,您没有使用JAR打包的静态资源,因此您的资源库确定应足够智能,以根据其执行方式使用备用位置。 (maven命令行,gradle命令行,IDE特定快速运行,IDE maven运行,IDE gradle运行等...)

您的ServletContextHandler应该在其servlet树中添加DefaultServlet(这实际上是为静态资源提供的)

示例:DefaultServletFileServer.java(来自embedded-jetty-cookbook项目)

import java.net.URI;
import java.net.URL;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.resource.Resource;

public class DefaultServletFileServer
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server();
        ServerConnector connector = new ServerConnector(server);
        connector.setPort(8080);
        server.addConnector(connector);

        // Figure out what path to serve content from
        ClassLoader cl = DefaultServletFileServer.class.getClassLoader();
        // We look for a file, as ClassLoader.getResource() is not
        // designed to look for directories (we resolve the directory later)
        URL f = cl.getResource("static-root/hello.html");
        if (f == null)
        {
            throw new RuntimeException("Unable to find resource directory");
        }

        // Resolve file to directory
        URI webRootUri = f.toURI().resolve("./").normalize();
        System.err.println("WebRoot is " + webRootUri);

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        context.setBaseResource(Resource.newResource(webRootUri));
        server.setHandler(context);

        ServletHolder holderPwd = new ServletHolder("default",DefaultServlet.class);
        holderPwd.setInitParameter("dirAllowed","true");
        context.addServlet(holderPwd,"/");

        server.start();
        server.join();
    }
}
相关问题