Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/88.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 通过servlet访问webapp文件夹中文件的正确路径_Html_Servlets - Fatal编程技术网

Html 通过servlet访问webapp文件夹中文件的正确路径

Html 通过servlet访问webapp文件夹中文件的正确路径,html,servlets,Html,Servlets,我的webapp文件夹中有一个“index.html”文件。现在我想通过我的servlet重定向到这个文件,但它总是给出异常,因为我不知道该放什么路径。我的代码: public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { // Must set the content type first

我的webapp文件夹中有一个“index.html”文件。现在我想通过我的servlet重定向到这个文件,但它总是给出异常,因为我不知道该放什么路径。我的代码:

public void service(HttpServletRequest request, 
          HttpServletResponse response) throws IOException {
        // Must set the content type first          
        RequestDispatcher view = request.getRequestDispatcher("webapp/index.html");
        try {
            view.forward(request, response);
        } catch (ServletException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
  }
我使用了“index.html”、“/index.html”、“/index.html”, “/webapp/index.html”、“/webapp/index.html”


我不知道如何访问这个文件。请提供帮助。

您的代码有两个问题:

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

    RequestDispatcher view = request.getRequestDispatcher("index.html");
    try {
        view.forward(request, response);
    } catch (ServletException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
  • 第一个问题是您正在重写service()方法。没有理由这样做,而且政府明确表示:

    从公共服务方法接收标准HTTP请求,并 将它们分派给此类中定义的doMethod方法。这 方法是的HTTP特定版本 service(javax.Servlet.ServletRequest, servlet.ServletResponse)方法不需要覆盖 此方法

    因此,请删除您的
    doService()
    方法。相反,实现一个包含
    doService()
    方法中的代码的
    doGet()
    方法

  • 第二个问题是指定html文件名的方式看起来不正确。我不知道您是如何组织您的项目的,但是如果您将index.html直接放在WebContent下,您可以使用“/index.html”“index.html”引用该文件:

    指定的路径名可能是相对的,但不能扩展 在当前servlet上下文之外。如果路径以“/”开头,它将 被解释为相对于当前上下文根

  • 尝试删除
    service()
    方法并添加包含代码的
    doGet()
    方法:

        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
    
        RequestDispatcher view = request.getRequestDispatcher("index.html");
        try {
            view.forward(request, response);
        } catch (ServletException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }