Servlet图像过滤器无法在线主机

时间:2016-05-02 11:41:01

标签: java image servlets filter openshift

我正在学习Servlet。今天我尝试制作一个Servlet过滤器,按照教程,想法是:

  • 我有一张默认照片 - notFound.jpg
  • 过滤器将捕获所有图像请求,* .jpg * .png * .gif ...
  • 如果文件存在,则返回,否则返回notFound.jpg

我的本​​地一切正常(我使用Eclipse和Tomcat 8)。

但是当我在一台在线主机上运行它 - 运行Tomcat 7的Openshift时,我无法访问任何照片:

+在htm文件中,照片显示为未找到来源

+现在指向notFound.jpg的照片的所有绝对网址,而notFound.jpg本身并不返回任何内容,只是一个空白页。

我认为问题是我无法在在线主机上获取realPath(request.getServletContext()。getRealPath("");)但我无法解决这个问题。

非常感谢您阅读本文

这是我的过滤器:

@WebFilter(urlPatterns = {" .png"," .jpg"," * .gif"}, initParams = {

@WebInitParam(name =" notFoundImage",value =" /img/notFound.jpg")})

public class ImageFilter实现Filter {

private String notFoundImage;

public ImageFilter() {
}

public void destroy() {
}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;

    String servletPath = req.getServletPath();

    String realRootPath = request.getServletContext().getRealPath("");

    String imageRealPath = realRootPath + servletPath;

    File file = new File(imageRealPath);

    if (file.exists()) {
        chain.doFilter(request, response);
    } else if (!servletPath.equals(this.notFoundImage)) {

        HttpServletResponse resp = (HttpServletResponse) response;

        resp.sendRedirect(req.getContextPath() + this.notFoundImage);
    }

}

public void init(FilterConfig fConfig) throws ServletException {
    notFoundImage = fConfig.getInitParameter("notFoundImage");
}

}

0 个答案:

没有答案