Пример интеграции с Struts 2 Hibernate

Struts 2 + Hibernate пример интеграции

Скачать -Struts2-Hibernate-Integration-Example.zip

В Struts2 нет официальных плагинов для интеграции фреймворка Hibernate. Но вы можете обойти следующие шаги:

  1. Зарегистрируйте пользовательскийServletContextListener.

  2. В классеServletContextListener инициализируйтеHibernate session and store it into the servlet context.

  3. В классе действийget the Hibernate session from the servlet context и выполните задачу гибернации как обычно.

Смотрите отношения:

Struts 2 <-- (Servlet Context) ---> Hibernate <-----> Database

В этом руководстве он показывает простой клиентский модуль (функция добавления и перечисления), разработанный вStruts 2, и выполняет операцию с базой данных с помощьюHibernate. Часть интеграции использует вышеуказанный механизм (сохранение и извлечение сеанса Hibernate в контексте сервлета).

Этот обходной путь очень похож на классическийStruts 1.x and Hibernate integration, только классический Struts 1.x использует плагины Struts; В то время как Struts 2 использует общий слушатель сервлетов.

1. Структура проекта

Смотрите эту полную структуру папок проекта.

Struts 2 Hibernate integration example

2. MySQL табличный скрипт

Создайте таблицу клиентов для демонстрации. Вот скрипт таблицы SQL.

DROP TABLE IF EXISTS `example`.`customer`;
CREATE TABLE  `example`.`customer` (
  `CUSTOMER_ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `NAME` varchar(45) NOT NULL,
  `ADDRESS` varchar(255) NOT NULL,
  `CREATED_DATE` datetime NOT NULL,
  PRIMARY KEY (`CUSTOMER_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

3. зависимость

Получите библиотеки зависимостей Struts2, Hibernate и MySQL.

//...
    
    
            org.apache.struts
        struts2-core
        2.1.8
        

    
    
        mysql
        mysql-connector-java
        5.1.9
    

    
    
        org.hibernate
        hibernate
        3.2.7.ga
    

    
    
        dom4j
        dom4j
        1.6.1
    

    
        commons-logging
        commons-logging
        1.1.1
    

    
        commons-collections
        commons-collections
        3.2.1
    

    
        cglib
        cglib
        2.2
    
    

    
    
        antlr
        antlr
        2.7.7
    
    
//...

4. Hibernate Stuffs

Модель и конфигурация Hibernate.

Customer.java - создать класс для таблицы клиентов.

package com.example.customer.model;

import java.util.Date;

public class Customer implements java.io.Serializable {

    private Long customerId;
    private String name;
    private String address;
    private Date createdDate;

    //getter and setter methods
}

Customer.hbm.xml - файл сопоставления гибернации для клиента.




    

        
            
            
        
        
            
        
        
            
        
        
            
        
    

hibernate.cfg.xml - файл конфигурации базы данных Hibernate.




  
    false
    password
    jdbc:mysql://localhost:3306/example
    root
    org.hibernate.dialect.MySQLDialect
    true
    true
    false
    
  

5. Hibernate ServletContextListener

СоздайтеServletContextListener и инициализируйтеHibernate session and store it into the servlet context.

HibernateListener .java

package com.example.listener;

import java.net.URL;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateListener implements ServletContextListener{

    private Configuration config;
    private SessionFactory factory;
    private String path = "/hibernate.cfg.xml";
    private static Class clazz = HibernateListener.class;

    public static final String KEY_NAME = clazz.getName();

    public void contextDestroyed(ServletContextEvent event) {
      //
    }

    public void contextInitialized(ServletContextEvent event) {

     try {
            URL url = HibernateListener.class.getResource(path);
            config = new Configuration().configure(url);
            factory = config.buildSessionFactory();

            //save the Hibernate session factory into serlvet context
            event.getServletContext().setAttribute(KEY_NAME, factory);
      } catch (Exception e) {
             System.out.println(e.getMessage());
       }
    }
}

Зарегистрируйте слушателя в файле web.xml.
web.xml




  Struts 2 Web Application

  
    struts2
    
      org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    
  

  
    struts2
    /*
  

  
    
      com.example.listener.HibernateListener
    
  

6. действие

В классе Action введитеget the Hibernate session from the servlet context и выполните задачу Hibernate как обычно.

CustomerAction.java

package com.example.customer.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.example.customer.model.Customer;
import com.example.listener.HibernateListener;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class CustomerAction extends ActionSupport
    implements ModelDriven{

    Customer customer = new Customer();
    List customerList = new ArrayList();

    public String execute() throws Exception {
        return SUCCESS;
    }

    public Object getModel() {
        return customer;
    }

    public List getCustomerList() {
        return customerList;
    }

    public void setCustomerList(List customerList) {
        this.customerList = customerList;
    }

    //save customer
    public String addCustomer() throws Exception{

        //get hibernate session from the servlet context
        SessionFactory sessionFactory =
             (SessionFactory) ServletActionContext.getServletContext()
                     .getAttribute(HibernateListener.KEY_NAME);

        Session session = sessionFactory.openSession();

        //save it
        customer.setCreatedDate(new Date());

        session.beginTransaction();
        session.save(customer);
        session.getTransaction().commit();

        //reload the customer list
        customerList = null;
        customerList = session.createQuery("from Customer").list();

        return SUCCESS;

    }

    //list all customers
    public String listCustomer() throws Exception{

        //get hibernate session from the servlet context
        SessionFactory sessionFactory =
             (SessionFactory) ServletActionContext.getServletContext()
                     .getAttribute(HibernateListener.KEY_NAME);

        Session session = sessionFactory.openSession();

        customerList = session.createQuery("from Customer").list();

        return SUCCESS;

    }
}

7. Страница JSP

Страница JSP, чтобы добавить и перечислить клиента.

customer.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>





Struts 2 + Hibernate integration example

Add Customer

All Customers

Customer Id Name Address Created Date


8. struts.xml

Связать все это ~





  

  

    
       pages/customer.jsp
    

    
        pages/customer.jsp
    

  

9. Demo

Доступ к клиентскому модулю:http://localhost:8080/Struts2Example/listCustomerAction.action

Struts 2 Hibernate Add Customer

Заполните поля имени и адреса, нажмите кнопку «Отправить», информация о клиенте будет указана немедленно.

Struts2 Hibernate List Customer

Related