Java EE Tomcat DefaultServlet扩展不适用于静态文件

时间:2016-02-27 12:41:05

标签: java tomcat servlets

我正面临着基于Servlets在Java EE中编写Web应用程序的问题。一切都还可以,但我无法弄清楚如何正确地将jscss个文件附加到我的html页面。我已经在网上阅读了一些关于此问题的答案和帖子,我不想编写自己的servlet来执行此操作,因为据我所知Tomcat提供DefaultServlet并且它可以满足我的需求。现在,我尝试编写这个类的实现,在这里:

package xx.xx.xx;

import java.io.File;
import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.servlets.DefaultServlet;

@WebServlet(urlPatterns={"/js/*","/css/*","/libs/*"})
public class StaticContent extends DefaultServlet {

    public StaticContent() {
        super();
    }

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        File f = new File(StaticContent.class.getProtectionDomain().getCodeSource().getLocation().getPath()+"../css/global.css");
        System.out.println("_____HERE " + request.getRequestURL() + " | " + f.exists());
        super.doGet(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        throw new UnsupportedOperationException();
    }

}

我不明白。它仍然无法正常工作。 java文件系统识别它并在true上返回file.exists()但服务器没有。当我尝试从浏览器访问它时,它也会失败404。任何想法我应该在这做什么?资产文件紧挨着html中的WEB-INF

1 个答案:

答案 0 :(得分:0)

好的,我在这里工作的是我的doGet方法:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String arr[] = request.getRequestURL().toString().split("/");
    String file = arr[arr.length-1];
    String folder = arr[arr.length-2];
    request.getRequestDispatcher("/WEB-INF/"+folder+"/"+file).forward(request, response);
}