⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 contactlist.java

📁 java对象/关系数据库映射工具hibernate和java web 框架struts结合的实例
💻 JAVA
字号:
//$Id: ContactList.java,v 1.6 2003/03/14 20:24:49 thusted Exp $
package eg1;

import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eg.Contact;
import eg.User;
import net.sf.hibernate.Hibernate;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import struts.HibernatePlugIn;


/**
 * Disconnect example,
 * aka "long transactions with versioning" approach.
 * <p>
 * An example DispatchAction using a disconnectable Hibernate session
 * to store persistent state.
 * This is the first of three examples presented,
 * and is the most efficient in terms of database access.
 * However, this approach requires that the Session be kept in
 * the user's HttpSession between action invocations.
 * <p>
 * This is the "long transactions with versioning" approach where
 * automatic version checking (optimistic locking) ensures
 * isolation even when the Session spans multiple database
 * transactions.
 * <p>
 * The Session-per-Session approach can be its quite good for some
 * applications (extra caching), not so good for others (extra resources).
 * This approach should only be used with versioned data,
 * and it is a good practice to time-out (expire) the Session from
 * time to time, as the cached data may become stale.
 * <p>
 * Note that all three examples disconnect or close the session
 * before returning.
 * If a presentation page uses a naked entity (e.g. User), and lazy
 * initialization is enabled, it might try to access data that was
 * not been retrieved.
 * <p>
 * Alternatives include:
 * <ul>
 * <li> applying hibernate.initalize on any proxy or lazy collection
 * exposed to the presentation layer
 * <li> using a filter to open and close a session for each request
 * <li> using a callback method (e.g. Maverick's **).
 * </ul>
 * <p>
 * In this example, hibernate.initialize() is called since all
 * the contacts are rendered by the page (regardless).
 *
 */

public class ContactList extends DispatchAction {

    public static String SUCCESS = "success";
    public static String USER = "user";
    public static String WELCOME = "welcome";

    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {

        ActionForward forward = null;
        Session session = null;
        EgForm egForm = (EgForm) form;

        try {
            session = obtainSession(request);
            egForm.setSession(session);

            forward = super.execute(mapping, form, request, response);

            if (null != session) {
                // force initialization of User object
                // only necessary if lazy is enabled
                User user = getUser(request);
                if (null!=user) {
                    Hibernate.initialize(user);
                    Hibernate.initialize(user.getContacts());
                }
                // commit any change made by a sub-process
                session.flush();
                session.connection().commit();
            }
        } catch (HibernateException e) {
            doException(e, request, session);
        } finally {
            doFinally(session);
        }

        releaseSession(session);
        return forward;

    }


    /**
     * Acquire the session, by whatever means necessary.
     *
     * @param request
     * @return
     * @throws HibernateException
     */
    public Session obtainSession(HttpServletRequest request) throws HibernateException {
        return HibernatePlugIn.reconnect(request);
    }

    /**
     * Close or disconnect the session, as appropriate.
     *
     * @param session
     * @throws HibernateException
     */
    public void releaseSession(Session session) throws HibernateException {
        session.disconnect(); // keep for next time
    }

    /**
     * Handle an exception (thrown by one of our dispatch methods).
     *
     * (This is not a good place for an extension point,
     * but it is being used for the sake of example.)
     *
     * @param e The Exception we are handling
     * @param request The request we are processing.
     * @param session  The Hibernate session we were using.
     * @throws Exception To be handled by the application
     */
    public void doException(Exception e, HttpServletRequest request, Session session) throws Exception {
        // if error, don't leave the session in an invalid state
        request.getSession().invalidate();
        if (null != session) {
            session.connection().rollback();
            session.close();
        }
        throw e;
    }

    /**
     * Perform any "finally" tasks,
     * such as closing a session if it is not cached.
     *
     * (This is not a good place for an extension point,
     * but it is being used for the sake of example.)
     */
    public void doFinally(Session session) throws HibernateException {
        // nothing to do for this class
    }


    // -- DISPATCH METHODS AND HELPERS--

    public static void setUser(HttpServletRequest request, User user) {
        if (null != user) {
            request.getSession().setAttribute(USER, user);
        } else {
            request.getSession().removeAttribute(USER);
        }
    }

    public static User getUser(HttpServletRequest request) {
        return (User) request.getSession().getAttribute(USER);
    }

    public static String HQL_FIND_USER = "FROM user IN class eg.User WHERE user.userName = ?";

    public ActionForward login(ActionMapping mapping,
                               ActionForm form,
                               HttpServletRequest request,
                               HttpServletResponse response) throws Exception {

        EgForm egForm = (EgForm) form;
        String userName = egForm.getUserName(); // unauthenticated

        Session s = egForm.getSession();
        List l = s.find(HQL_FIND_USER, userName, Hibernate.STRING);

        User user;
        if (l.size() > 0) {
            user = (User) l.get(0);
        } else {
            user = new User(userName);
            s.save(user);
        }

        setUser(request, user);
        egForm.reset(mapping, request);

        return mapping.findForward(SUCCESS);
    }

    public ActionForward update(ActionMapping mapping,
                                ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response) throws Exception {

        EgForm egForm = (EgForm) form;
        getUser(request).setName(egForm.getName());
        return mapping.findForward(SUCCESS);
    }

    public ActionForward delete(ActionMapping mapping,
                                ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response) throws Exception {

        User user = getUser(request);
        EgForm egForm = (EgForm) form;
        egForm.getSession().delete(user);
        setUser(request, null);
        return mapping.findForward(WELCOME);
    }

    public ActionForward addEntry(ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {

        EgForm egForm = (EgForm) form;
        Contact contact = new Contact();
        BeanUtils.copyProperties(contact, egForm);
        getUser(request).addContact(contact);
        egForm.getSession().save(contact);
        egForm.resetContact();
        return mapping.findForward(SUCCESS);
    }

    public ActionForward deleteEntry(ActionMapping mapping,
                                     ActionForm form,
                                     HttpServletRequest request,
                                     HttpServletResponse response) throws Exception {

        EgForm egForm = (EgForm) form;
        Session s = egForm.getSession();
        Long contactId = egForm.getId();
        User user = getUser(request);

        Iterator contacts = user.getContacts().iterator();
        while (contacts.hasNext()) {
            Contact contact = (Contact) contacts.next();
            if (contact.getId().equals(contactId)) {
                user.removeContact(contact);
                s.delete(contact);
                break;
            }
        }
        return mapping.findForward(SUCCESS);
    }

    public ActionForward display(ActionMapping mapping,
                                     ActionForm form,
                                     HttpServletRequest request,
                                     HttpServletResponse response) throws Exception {

        HibernatePlugIn.expire(request);
        return mapping.findForward(SUCCESS);
    }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -