防止未登录的用户直接重写URL访问系统

来源:互联网 发布:蒙泰打印管理系统端口 编辑:程序博客网 时间:2024/05/21 17:57

    最近在开发系统的时候,碰到个问题,就是未登录的用户可以通过重写url登录他本不能登录的系统。

经过研究,终于把此问题解决了。呵~

   思路是:每当有用户成功登录系统时,把其信息保存到session中。在相应被访问的页面,其对应的bean中的构造函数来获得session 中用户对象,若用户对象为空,则表明此用户是未登录的,使其跳转到登录页面。

 

   session 取得代码

 

  public class SessionHelper
  {

    private static final String OA_WEB_SESSION="OAWebSession";
    private static HttpSession getSession()
    {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        return request.getSession();
    }

    public static OAWebSession getOAWebSession()
    {
        Object session = getSession().getAttribute(OA_WEB_SESSION);
        if (session == null)
        {
            session = new OAWebSession();
            getSession().setAttribute(OA_WEB_SESSION, session);
        }
        return (OAWebSession) session;
    }

    public static void removeOAWebSession()
    {
        getSession().removeAttribute(OA_WEB_SESSION);
    }
}

 

  在用户成功登录后把其信息储存到session中

            User user = new User();
            user.login(userID, password);
            SessionHelper.getOAWebSession().setUser(user);

 

   被访问的页面对应的bean

 

   public class Top{

     public Top(){

              user = SessionHelper.getOAWebSession().getUser();
             if (user == null) {
              NavigateHelper.redirect("Logon.jsp");
        }

    }

  }

 

  redirect 方法如下:

   public class NavigateHelper
{
    public static void redirect(String url)
    {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        try
        {
            response.sendRedirect(url);
        }
        catch (IOException ex)
        {
            ExceptionHelper.jumpToErrorPageWithResponseComplete(ex, SessionHelper.getOAWebSession());
        }
    }
}

 

  注明: 由于jsf 是先走构造函数,才走get方法,所以get方法要加个对象或值取得为空的判断。

  注明: 此块功能只对未登录的用户有效,登录了但没权挟的在研究中。

原创粉丝点击