我正在学习Servlet。今天我尝试制作一个Servlet过滤器,按照教程,想法是:
我的本地一切正常(我使用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");
}
}