使用过滤器的会话管理

时间:2013-06-25 13:59:52

标签: java jsf-2 servlet-filters

我正在使用过滤器进行会话管理我已编写方法并使用managedbean注释我正在尝试将验证成功发送到过滤器。

@ManagedBean(name = "customer")
@SessionScoped
public class CustomerBean implements Serializable{


    public String checkValidCustomer(){
         FacesContext context = FacesContext.getCurrentInstance();
         HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
         HttpSession session = request.getSession(true);
        Customer cust = new Customer();
        cust.setUsername(getUsername());
        cust.setPassword(getPassword());
        String returnValue = customerBo.checkValidCustomer(cust); 
        if(returnValue == "success"){
        session.setAttribute("customer", returnValue);
        }
        else
        {
            session.setAttribute("customer", null);
        }
        return returnValue;

我在retunValue字符串中取得了成功,所以我试图将值作为值传递给managedBean注释。而myfilter代码就像。

@WebFilter("/faces/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {    
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String cust = (String) req.getSession().getAttribute("customer");
        if (cust != null && cust.equals("success")) {
            chain.doFilter(request, response);
        } else {
            resp.sendRedirect(req.getContextPath() + "/faces/default.xhtml");
        }
    }

我为String cust获取空值,当我打开登录页面时,它显示此网页有一个重定向循环。你能告诉我哪里做错了..

1 个答案:

答案 0 :(得分:0)

试试这个......

HttpServletRequest request = (HttpServletRequest) req;
          HttpServletResponse response = (HttpServletResponse) resp;
          System.out.println("Inside the filter.............."  );
          HttpSession session = request.getSession();
          User u = null;
          if(session.getAttribute("customer")!=null){
              u = (User) session.getAttribute("customer");
          }       
          if (u!= null)
          {
              System.out.println("user does exits.." + u.getUname() );// u can see who was logged here
              chain.doFilter(req, resp);          
          }else{
              System.out.println("user does exits..");        
          }