了解servlet过滤器重定向行为

时间:2015-03-02 11:41:58

标签: http servlets redirect servlet-filters

我有以下过滤器代码:

@WebFilter(urlPatterns = "/faces/*")
public class AuthenticationFilter implements Filter {

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    HttpSession session = req.getSession(true);

    System.out.println("No Filtering");
    chain.doFilter(request, response);

}  

在NetBeans中启动项目将导致两次打印“No Filtering”,一次用于拦截请求,第二次用于拦截响应。
到目前为止一直很好,但直到现在还没有过滤。更新网页或使用POST方法提交表单将以相同的方式生成。 现在添加以下过滤条件:

if ( !req.getRequestURI().toLowerCase().endsWith("/index.xhtml")
            &&(session.isNew() || session.getAttribute("username") == null))    {
        System.out.println("directed");
        res.sendRedirect(req.getContextPath() + "/index.xhtml");
    }else{
    System.out.println("not directed");
    chain.doFilter(request, response);}  

将按预期导致打印“定向”一次。现在更新网页或提交表格时出现了问题,即使是“无过滤”也不打印?似乎过滤器没有应用于HTTP请求,我不明白为什么?
这是我的web.xml文件:

<context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
</context-param>
<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>
<welcome-file-list>
    <welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>  

UPDATE1:
我尝试将HTTP响应状态设置为302,303,307,但没有任何变化。

1 个答案:

答案 0 :(得分:0)

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException 
    {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        HttpSession session = req.getSession(true);
        String requestPath = req.getRequestURI();
        PrintWriter out =res.getWriter();
        if(session.getAttribute("UserName")==null)// Check for null user
            {
            if(needsAuthentication(requestPath)) //If user is on Login.jsp it lets user to stay there
                {
                chain.doFilter(req, res);
                }
            else
                {//If user is not on login page with session attribute null it will check if the form has submitted user name and password
                    if((req.getParameter("username"))==null)
                        {//If no user name and password is submitted it means user is trying to access other pages without login so 
                        //this condition will land user on login page 
                        out.println("Please Login !");
                        RequestDispatcher rd =req.getRequestDispatcher("Login.jsp");
                        rd.include(req, res);
                        }
                    else
                            {
                                if ((req.getParameter("username")).equals("admin")&&(req.getParameter("password").equals("123")))
                                    {//If correct credentials are submitted user session is started 
                                        LoginUser user =new LoginUser();
                                        user.setUserName("admin");
                                        session.setAttribute("UserName", user.getUserName());
                                        session.setMaxInactiveInterval(60);
                                        chain.doFilter(req, res);
                                    }
                                else 
                                        {//This will send user to login page again when wrong credentials are set
                                        out.print("Incorrect UserName or Password");
                                        RequestDispatcher rd =req.getRequestDispatcher("Login.jsp");
                                        rd.include(req, res);
                                        }
                            }
                }       
            }
        else//This else part is checked when the user session is not null 
            {
            if(session.getAttribute("UserName").equals("admin"))//if user is valid it will continue the flow   
                {
                System.out.println("In Second If");
                chain.doFilter(req, res);
                }
            else        
                { //if user is invalid will land up on login page
        System.out.println("In Second Else");
        req.getRequestDispatcher("Login.jsp").forward(request, response);
                }

            }
        }

尝试使用这个和她的方法

private boolean needsAuthentication(String requestPath) {
         {
               String validNonAuthenticationUrls ="/Login.jsp";

                    if (requestPath.endsWith(validNonAuthenticationUrls)) {
                        return true;
                    }
                }
                return false;
            }   
         }