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

📄 contactlistrepo.java

📁 java对象/关系数据库映射工具hibernate和java web 框架struts结合的实例
💻 JAVA
字号:
//$Id: ContactList2.java,v 1.1.1.1 2003/03/09 12:37:45 thusted Exp $
package eg1;

import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
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.MappingException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
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.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.config.ModuleConfig;


/**
 * An example servlet using a disconnectable Hibernate session
 * to store persistent state. Of the three examples presented,
 * this is the most efficient in terms of database access.
 * However, this approach requires that the Session be kept in
 * the user's HttpSession between servlet invocations. This is
 * the "long transactions with versioning" approach where
 * automatic version checking (optimistic locking) ensures
 * isolation even when the Session spans multiple database
 * transactions.
 */

public class ContactListRepo extends DispatchAction implements PlugIn {

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

    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 = reconnect(request);
            egForm.setSession(session);

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

            if (null != session) {
                // commit any change made by a sub-process
                session.flush();
                session.connection().commit();
            }
        } catch (HibernateException e) {
            // if error, don't leave the session in an invalid state
            request.getSession().invalidate();
            if (null != session) {
                session.connection().rollback();
                session.close();
            }
            throw e;
        }

        session.disconnect(); // keep for next time
        return forward;

    }

    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

        // User Repository.login(String)
        // - List Repository.findUser(String)
        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 Repository.newUser(String)
            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;
        // User Repository.update(User,String);
        getUser(request).setName(egForm.getName());
        return mapping.findForward(SUCCESS);
    }

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

        // Boolean Repository.delete(Session,User);
        User user = getUser(request);
        EgForm egForm = (EgForm) form;
        egForm.getSession().delete(user);
        setUser(request, null);
        return mapping.findForward(SUCCESS);
    }

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

        // Contact Repository.addEntry(Session,User,Object);
        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 {

        // Boolean Repository.deleteEntry(Session,User,Long);
        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);
    }

    // ---------------------------------------------------- PLUG IN

    /**
     * A field to store the reference to our SessionFactory.
     * Can close and dispose if not null.
     */
    private SessionFactory sf;

    /**
     * A public identifer for the persistence session,
     * kept in servlet session ("client") scope.
     */
    public static String SESSION = "session";

    /**
     * A public identifer for the session factory,
     * kept in application ("global") scope.
     */
    public static String SESSION_FACTORY = "session_factory";

    /**
     * Grab and reconnect the user's Session from the HttpSession,
     * or open a new Session
     * @param request The requeset we are servicing
     * @return An open session
     * @throws HibernateException if session cannot be instantiated
     */
    public static Session reconnect(HttpServletRequest request)
            throws HibernateException {

        SessionFactory sf = (SessionFactory)
                request.getSession().getServletContext().getAttribute(SESSION_FACTORY);
        if (null == sf) {
            throw new HibernateException(SESSION_FACTORY);
        }

        Session s = (Session) request.getSession(true).getAttribute(SESSION);
        if (null == s) {
            s = sf.openSession();
            request.getSession().setAttribute(SESSION, s);
        } else {
            s.reconnect();
        }
        return s;
    }

    /**
     * The classes with mappings to add to the Configuration are enumerated here.
     * There should be a "${class}.hbm.xml" mapping file for each class
     * stored with each compiled class file.
     * <p>
     * To complete the Hibernate setup, there must be a valid "hiberate.properties"
     * file under the "classes" folder (root of the classpath),
     * which specifies the details of the database hookup.
     * <p>
     * The mapping documents and properties file is all that Hibernate requires.
     * <p>
     * A JDBC Driver is not included in this distribution and *must* be
     * available on your server's or container's classpath
     * (e.g., the Tomcat common/lib directory).
     *
     * @return A Configuration object
     * @throws MappingException if any the mapping documents can be rendered.
     */
    private static final Configuration createConfiguration()
            throws MappingException {
        return new Configuration()
                .addClass(User.class)
                .addClass(Contact.class);
    }

    public void init(ActionServlet servlet, ModuleConfig config)
            throws ServletException {

        SessionFactory exists = (SessionFactory)
                servlet.getServletContext().getAttribute(SESSION_FACTORY);
        if (null != exists) return; // already got one

        try {
            sf = createConfiguration().buildSessionFactory();
        } catch (HibernateException e) {
            e.printStackTrace();
            servlet.log(e.toString());
            throw new ServletException(e);
        }

        servlet.getServletContext().setAttribute(SESSION_FACTORY, sf);
    }

    public void destroy() {
        if (null != sf) {
            try {
                sf.close();
            } catch (HibernateException e) {
                // too late now
            }
        }
        sf = null;
    }

}

⌨️ 快捷键说明

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