创建用于处理公共servlet请求和事务操作的静态方法

时间:2015-09-17 04:33:23

标签: java hibernate java-ee servlets

考虑任何servlet之外的这些静态方法。所有这些都从servlet过滤器中检索一个hibernate会话。

public static User findUser(HttpServletRequest request) {
    Session session = (Session)request.getAttribute("session"); // org.hibernate.Session
    User user = (User)session.createQuery("from User u where u.email like :email and u.password like :password").setParameter("email", request.getParameter("email")).setParameter("password", hash(request.getParameter("password"))).uniqueResult();
    return user;
}

public static User userExist(HttpServletRequest request) {
    Session session = (Session)request.getAttribute("session"); // org.hibernate.Session
    User user = (User)session.createQuery("from User u where u.email like :email").setParameter("email", request.getParameter("email")).uniqueResult();
    return user;
}

public static User loadUser(HttpServletRequest request) {
    Session session = (Session)request.getAttribute("session"); // org.hibernate.Session
    User user = session.load(User.class, (long)request.getSession().getAttribute("userid"));
    return user;
}

public static boolean existReservations(HttpServletRequest request, boolean checkCurrent) {
    Date checkInDate = getDate(request.getParameter("checkInDate"));
    Date checkOutDate = getDate(request.getParameter("checkOutDate"));
    List<Reservation> res = loadUser(request).getReservations();
    for (Reservation r : res) {
        if (checkInDate.compareTo(r.getCheckOutDate()) <= 0 && checkOutDate.compareTo(r.getCheckInDate()) >= 0) {
            if (checkCurrent && r.getReservationID() != Long.parseLong(request.getParameter("id"))) {
                continue;
            }
            return true;                
        }
    }
    return false;
}

我将不得不多次调用这些方法,因此它们属于Utils类。现在,我完全相信,如果符合以下条件,我会一直打电话给他们:

  • 我在servlet中。
  • hibernate会话已打开
  • 可以使用HTTPSession和“userid”属性。
  • 如果是预订方法,则可以使用参数“id”

现在我发现这样做会使我的servlet代码更短。我个人认为这样做没有问题,我没有修改HTTPServletRequest中的任何属性或参数。我见过很多问题,问这是否可行。但这是不好的做法还是我做得很好?是否存在采用这种方法使坏事发生的情况?

0 个答案:

没有答案