阻止Web应用程序中文件的直接URL访问

时间:2017-06-01 04:40:40

标签: java

我有一个java Web应用程序,其中图像存储在一个文件夹中。

现在的问题是,用户能够使用URL访问图像,如下所示。

http://localhost/Webapplication/images/image.jpg 

我想阻止驻留在Web应用程序的图像文件夹中的图像文件的直接URL访问。但是这些图像应该通过htlm页面显示。

我在JBoss应用程序服务器上运行,已经用谷歌搜索了这个,但最终得到了.htaccess解决方案,这对我的java应用程序没有帮助。 任何帮助将非常感激。 感谢

1 个答案:

答案 0 :(得分:0)

  - You just used AuthenticationFilter in you Application.
  - AUTH_KEY is define LoginController to get userId
  - @Secured is defined web.xml file for filter this path.
  - @/Secured/temp/ is defined for image in my project directory.
  - @/Secured/login.xhtml is defined after servlet configure initial it will    login.xhtml redirect. 

遵循以下代码:

import java.io.IOException;
import javax.faces.application.ResourceHandler;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
*
 * @author Md. Amran Hossain
*/
@WebFilter("/Secured/*")
public class AuthenticationFilter implements Filter {

    private FilterConfig config;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.config = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse    response,     FilterChain chain) throws IOException, ServletException {
    if (((HttpServletRequest) request).getSession().getAttribute(LoginController.AUTH_KEY) == null
            && !((HttpServletRequest) request).getRequestURI().endsWith("/Secured/login.xhtml")
            && !((HttpServletRequest) request).getRequestURI().contains("/Secured/temp/")
            && !((HttpServletRequest) request).getRequestURI().startsWith(((HttpServletRequest) request).getContextPath() + "/Secured" + ResourceHandler.RESOURCE_IDENTIFIER)) {
        ((HttpServletResponse) response).sendRedirect(((HttpServletRequest) request).getContextPath() + "/Secured/login.xhtml");
    } else {
        chain.doFilter(request, response);
    }
}

@Override
public void destroy() {
    this.config = null;
}
}

将此配置放在web.xml中

<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/Secured/*</url-pattern>
</servlet-mapping>