从Jetty Serverlet doGet方法中的resources文件夹中显示静态HTML文件 [英] Display static HTML file from resources folder in Jetty Serverlet doGet method

查看:80
本文介绍了从Jetty Serverlet doGet方法中的resources文件夹中显示静态HTML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个servlet,我想返回资源,或者至少返回资源中的html,index.html位于我的webapps文件夹中.

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();
    }
}

这是我当前的doGet方法.当前打印位置是我希望servlet返回的index.html文件的字符串值.

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>");

}

推荐答案

请勿同时使用ResourceHandler和ServletContextHandler . (先前的回答)

完全丢弃ResourceHandler.

Drop the ResourceHandler entirely.

拖放IndexServlet(不需要).

Drop the IndexServlet (you don't need it).

创建一个src/main/webapp/index.html(如果使用Maven和WAR项目类型),然后将HTML编写为HTML.

Create a src/main/webapp/index.html (if using Maven and a WAR project type) and write the HTML as HTML.

ServletContextHandler需要一个资源库.

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

The Resource Base should be a full (absolute) path (not relative) to your post-processed static content. If your build copies/creates/modifies resources, you need to be aware of that and use an alternate directory location. It is possible to use a jar:file:// directory location as well.

从IDE运行/调试/测试时,您没有使用JAR打包的静态资源,因此您的资源库确定应该足够聪明,可以根据执行方式使用备用位置. (maven命令行,gradle命令行,特定于IDE的快速运行,IDE maven运行,IDE gradle运行等...)

When you run / debug / test from your IDE you are not using a JAR packaged static resources, so your Resource Base determination should be smart enough to use alternate locations depending on how it is being executed. (maven command line, gradle command line, IDE specific quick run, IDE maven run, IDE gradle run, etc ...)

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

Your ServletContextHandler should have a DefaultServlet added to its servlet tree (this is what actually serves static resources)

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

Example: DefaultServletFileServer.java (from embedded-jetty-cookbook project)

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();
    }
}

这篇关于从Jetty Serverlet doGet方法中的resources文件夹中显示静态HTML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆