2012-06-11 30 views
1

我创建使用JSF,休眠,春天的Web应用程序。我添加了检查会话的过滤器。我的滤波代码为:的Java FilterImplementation会话检查

public class AdminFilter implements Filter{ 

    private ArrayList<String> urlList; 

    @Override 
    public void init(FilterConfig filterConfig) throws ServletException { 
     String urls = filterConfig.getInitParameter("avoid-urls"); 
     StringTokenizer token = new StringTokenizer(urls, ","); 
     urlList = new ArrayList<String>(); 

     while (token.hasMoreTokens()) { 
      urlList.add(token.nextToken()); 
     } 
    } 

    // Checking if user is logged in 
    @Override 
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 
       HttpServletRequest req= (HttpServletRequest) request; 
     HttpServletResponse resp= (HttpServletResponse) response; 
     String url = req.getServletPath(); 
     HttpSession session = req.getSession(); 
       if(!urlList.contains(url) && session.getAttribute("user")==null) 
       { 
        resp.sendRedirect(req.getContextPath() + "/backend/login/index.xhtml"); 

       } 
      chain.doFilter(req, resp); 
    } 

    @Override 
    public void destroy() { 
     // throw new UnsupportedOperationException("Not supported yet."); 
    } 

} 

在过滤器的init方法我有哪个会话检查应该被跳过,像登录页面本身的一些避免URL。这是工作正确的,但这个过滤器限制我的CSS,图像和JS载入登录页面。 建议我什么是我的过滤器的问题?

+0

跳过JS,CSS?,它应该是像'/ PATH/TO/CSS/FROM/WEBROOT/CSS /' –

+0

​​避免的URL /后端/login/index.xhtml

+0

你有CSS,JS,Images的任何参数吗?(正在使用登录页面)? –

回答

3

您的登录页面需要一些资源(CSS,JS,图片),这是从单独的请求浏览器请求将由过滤器截获并因为你没有一个跳过等资源请求的任何参数(使用上登录页面),它会阻止此请求

建议:

你可以使用Spring-Security,而不是在写你的投资的时候,它已经被配置

+0

好的,我明白了。非常感谢你的回答。 –

+0

欢迎:) –

3

根据您当前的配置得到了很大的灵活性, 目前如果该URL用于提取CSS,图像或任何其他资源,则您的过滤器将会忽略。

boolean staticResources = (url.contains("css") || url.contains("images")); 
if(!urlList.contains(url) && session.getAttribute("user")==null && !staticResources) { 
     resp.sendRedirect(req.getContextPath() + "/backend/login/index.xhtml"); 
} 

这将避免会话检查静态内容。这样做的

更好的办法将利用领域使用的声明性安全为Java EE Web Security一部分。你在`urlList`添加什么