Struts2Spring3Hibernate4

From campisano.org
Jump to navigation Jump to search

Vademecum

Create the project skeleton

mvn archetype:generate -DarchetypeArtifactId=maven-archetype-webapp -DgroupId=org.tSprStrHib -DartifactId=TestStruts2Spring3Hibernate4 -Dversion=0.1 -DinteractiveMode=false
cd TestStruts2Spring3Hibernate4


Configure the encoding to use [optional]

Edit the pom.xml and add the follow config

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  </properties>


Add the dependencies list

Find your libraries coordinates from http://search.maven.org/ and add at pom.xml file.

For example, edit pom.xml and replace the dependencies list with the follow:

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <!--scope>test</scope-->
    </dependency>

    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-config-browser-plugin</artifactId>
      <version>2.3.8</version>
     <!--scope>test</scope-->
    </dependency>

    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-spring-plugin</artifactId>
      <version>2.3.8</version>
    </dependency>

    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-dojo-plugin</artifactId>
      <version>2.3.8</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>3.2.0.RELEASE</version>
      <!--scope>test</scope-->
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>3.2.0.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>3.2.0.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>3.2.0.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>3.2.0.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>3.2.0.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.1.9.Final</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.22</version>
    </dependency>

    <dependency>
      <groupId>javax.persistence</groupId>
      <artifactId>persistence-api</artifactId>
      <version>1.0.2</version>
    </dependency>

  </dependencies>

Downolad and test the dependencies with the command

mvn clean install
mkdir -p src/main/java src/test/java


Create a new Eclipse Dynamic Web Project

Open Eclipse J2ee and create a new Dynamic Web Project in this way:

on menu, click on 'File' -> 'New' -> 'Other...'
select 'Web' -> 'Dynamic Web Project' and click 'Next ->'
'Project name:' "TestStruts2Spring3Hibernate4"
click 'Next ->'
select 'src' and click 'Remove'
click 'Finish'
on left panel, right click on 'TestStruts2Spring3Hibernate4' and select 'New' -> 'Folder'
'Folder name:' "main"
click on 'Advanced > >'
'Link to alternate location': "YOUR_CREATED_MAVEN_PROJECT_PATH/src/main/java"
click 'Finish'
on left panel, right click on 'TestStruts2Spring3Hibernate4/main' and select 'Build Path' -> 'Use as Source Folder'
on left panel, right click on 'TestStruts2Spring3Hibernate4' and select 'New' -> 'Folder'
'Folder name:' "test"
click on 'Advanced > >'
'Link to alternate location': "YOUR_CREATED_MAVEN_PROJECT_PATH/src/test/java"
click 'Finish'
on left panel, right click on 'TestStruts2Spring3Hibernate4/test' and select 'Build Path' -> 'Use as Source Folder'
on left panel, right click on 'TestStruts2Spring3Hibernate4/WebContent -> 'Delete' -> 'Ok'
on left panel, right click on 'TestStruts2Spring3Hibernate4' and select 'New' -> 'Folder'
'Folder name:' "WebContent"
click on 'Advanced > >'
'Link to alternate location': "YOUR_CREATED_MAVEN_PROJECT_PATH/src/main/webapp"
click 'Finish'
on left panel, right click on 'TestStruts2Spring3Hibernate4/WebContent/WEB-INF/' and select 'New' -> 'Folder'
click on 'Advanced > >'
'Link to alternate location': "YOUR_CREATED_MAVEN_PROJECT_PATH/target/TestStruts2Spring3Hibernate4/WEB-INF/lib"
click 'Finish'
on left panel, right click on 'TestStruts2Spring3Hibernate4/Java Resources/Libraries/Web App Libraries' and select -> 'Build Path' -> 'Remove from Build Path'
on left panel, select all files on 'TestStruts2Spring3Hibernate4/lib' and right click -> 'Build Path' -> 'Add to Build Path'


Test the project

Finally, you can run the example with your eclipse server or by

mvn tomcat:run


Create a first example

  • File 'TestStruts2Spring3Hibernate4/WebContent/WEB-INF/index.jsp'
<html>
    <head>
        <title>Index</title>
    </head>
    <body>
        <a href="config-browser/index.action">index struts actions</a>
    </body>
</html>


  • File 'TestStruts2Spring3Hibernate4/WebContent/WEB-INF/classes/struts.xml'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="default" extends="struts-default">
        <action name="listAllPersons" method="listAll" class="BeanActionPerson">
            <result name="success">person/list.jsp</result>
        </action>

        <action name="deletePerson" method="delete" class="BeanActionPerson">
            <result type="redirect">listAllPersons.action</result>
        </action>

        <action name="addPersonForm" class="BeanActionPerson">
            <result>person/add.jsp</result>
        </action>

        <action name="addPerson" method="add" class="BeanActionPerson">
            <result type="redirect">listAllPersons.action</result>
        </action>

    </package>

</struts>


  • File 'TestStruts2Spring3Hibernate4/WebContent/WEB-INF/web.xml'
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
        http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>TestStruts2Spring3Hibernate4</display-name>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>



    <!-- Spring beans -->
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/resources/log4j.properties</param-value>
    </context-param>
    
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>



    <!-- Struts 2 -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>*.action</url-pattern>
    </filter-mapping>

</web-app>


  • File 'TestStruts2Spring3Hibernate4/WebContent/WEB-INF/resources/log4j.properties'
### direct log messages to stdout ###
log4j.rootLogger=ERROR, console, file

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.SimpleLayout

# AdminFileAppender - used to log messages in the admin.log file.
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=logs/admin.log
log4j.appender.file.layout=org.apache.log4j.SimpleLayout

log4j.logger=DEBUG, console, file


  • File 'TestStruts2Spring3Hibernate4/WebContent/WEB-INF/applicationContext.xml'
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Database Configuration -->
    <import resource="resources/spring/data_source.xml"/>
    <import resource="resources/spring/hibernate.xml"/>

    <!-- Beans Declaration -->
    <import resource="resources/spring/beans/person.xml"/>

</beans>


  • File 'TestStruts2Spring3Hibernate4/WebContent/WEB-INF/resources/spring/data_source.xml'
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
            <value>WEB-INF/resources/database.properties</value>
        </property>
    </bean>

    <!-- Data Source Declaration -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

</beans>


  • File 'TestStruts2Spring3Hibernate4/WebContent/WEB-INF/resources/database.properties'
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/tSprStrHib
jdbc.username=tSprStrHib
jdbc.password=tSprStrHib


  • File 'TestStruts2Spring3Hibernate4/WebContent/WEB-INF/resources/spring/hibernate.xml'
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- Hibernate session factory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
 
        <property name="dataSource">
            <ref bean="dataSource"/>
        </property>
 
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>

        <property name="packagesToScan" value="org.tSprStrHib.entity"/>
    </bean>

    <!-- Transaction Manager is defined -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>


  • File 'TestStruts2Spring3Hibernate4/WebContent/WEB-INF/resources/spring/beans/person.xml'
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- DAO -->
    <bean id="BeanDAOPerson" class="org.tSprStrHib.hibernate.DAOPersonHibernate">
        <property name="SessionFactory" ref="sessionFactory"/>
    </bean>

    <!-- BO -->
    <bean id="BeanBOPerson" class="org.tSprStrHib.domain.BOPerson">
        <property name="DAOPerson" ref="BeanDAOPerson"/>
    </bean>

    <!-- Actions -->
    <bean id="BeanActionPerson" class="org.tSprStrHib.action.ActionPerson">
        <property name="BOPerson" ref="BeanBOPerson"/>
    </bean>

</beans>


  • File 'TestStruts2Spring3Hibernate4/WebContent/person/list.jsp'
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sx" uri="/struts-dojo-tags"%>
<html>
    <head>
        <title>Person List</title>
        <sx:head debug="true" cache="false" compressed="false"/>
    </head>
    <body>
        <p>Person List</p>
        <div><s:url id="addPerson" value="addPersonForm.action">
        </s:url><s:a href="%{addPerson}">Add</s:a></div>
        <s:if test="persons.size > 0">
            <table id="persons">
                <s:iterator value="persons">
                    <tr>
                        <td><s:property value="firstname"/></td>
                        <td><s:property value="lastname"/></td>
                        <td><s:url id="deletePerson" value="deletePerson.action">
                            <s:param name="id" value="id"/></s:url>
                            <s:a href="%{deletePerson}">Delete</s:a></td>
                    </tr>
                </s:iterator>
            </table>
        </s:if>
    </body>
</html>


  • File 'TestStruts2Spring3Hibernate4/WebContent/person/add.jsp'
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sx" uri="/struts-dojo-tags"%>
<html>
    <head>
        <title>Add Person</title>
        <sx:head debug="true" cache="false" compressed="false"/>
    </head>
    <body>
        <p>Add User</p>
        <s:form name="addPersonForm" method="post" action="addPerson.action">
            <s:textfield name="firstname" label="First Name"/>
            <s:textfield name="lastname" label="Last Name"/>
            <s:submit type="button" name="Add"/>
        </s:form>
    </body>
</html>


  • File 'TestStruts2Spring3Hibernate4/Java Resources/main/org/tSprStrHib/entity/Person'
package org.tSprStrHib.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "person")
public class Person
{
    @Id
    @Column
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    @Column
    private String firstname;
    @Column
    private String lastname;

    public int getId()
    {
        return id;
    }

    public void setId(int _id)
    {
        id = _id;
    }

    public String getFirstname()
    {
        return firstname;
    }

    public void setFirstname(String _firstname)
    {
        firstname = _firstname;
    }

    public String getLastname()
    {
        return lastname;
    }

    public void setLastname(String _lastname)
    {
        lastname = _lastname;
    }
}


  • File 'TestStruts2Spring3Hibernate4/Java Resources/main/org/tSprStrHib/persistence/DAOPerson'
package org.tSprStrHib.persistence;

import java.util.List;
import org.tSprStrHib.entity.Person;

public interface DAOPerson
{
    public void add(Person _person);
    public void save(Person _person);
    public void delete(Person _person);
    public List<Person> getAll();
    public Person getById(int _id);
}


  • File 'TestStruts2Spring3Hibernate4/Java Resources/main/org/tSprStrHib/hibernate/DAOHibernate'
package org.tSprStrHib.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public abstract class DAOHibernate
{
    private SessionFactory m_session_factory;
    public void setSessionFactory(SessionFactory _sessionFactory) { m_session_factory = _sessionFactory; }

    public Session getSession()
    {
        return m_session_factory.getCurrentSession();
    }
}


  • File 'TestStruts2Spring3Hibernate4/Java Resources/main/org/tSprStrHib/hibernate/DAOHibernatePerson'
package org.tSprStrHib.hibernate;

import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import org.tSprStrHib.entity.Person;
import org.tSprStrHib.persistence.DAOPerson;

public class DAOPersonHibernate extends DAOHibernate implements DAOPerson
{
    @Override
    @Transactional
    public void add(Person _person)
    {
        getSession().save(_person);
    }

    @Override
    @Transactional
    public void save(Person _person)
    {
        getSession().save(_person);
    }

    @Override
    @Transactional
    public void delete(Person _person)
    {
        getSession().delete(_person);
    }

    @Override
    @Transactional
    public List<Person> getAll()
    {
        @SuppressWarnings("unchecked")
        List<Person> list = (List<Person>) getSession().createCriteria(Person.class).list();

        return list;
    }

    @Override
    @Transactional
    public Person getById(int _id)
    {
        Person person = (Person) getSession().get(Person.class, _id);

        return person;
    }
}


  • File 'TestStruts2Spring3Hibernate4/Java Resources/main/org/tSprStrHib/domain/BOPerson'
package org.tSprStrHib.domain;

import java.util.List;
import org.apache.log4j.Logger;
import org.tSprStrHib.entity.Person;
import org.tSprStrHib.persistence.DAOPerson;

public class BOPerson
{
    private static final Logger LOGGER = Logger.getLogger(BOPerson.class.getName());

    private DAOPerson m_dao_person;
    public void setDAOPerson(DAOPerson _dao_person) { m_dao_person = _dao_person; }

    public void add(Person _person)
    {
        LOGGER.debug("Adding the following person: " + _person.getFirstname() + ", " + _person.getLastname());
        m_dao_person.add(_person);
    }

    public void delete(Person _person)
    {
        LOGGER.debug("Deleting the following person: " + _person.getFirstname() + ", " + _person.getLastname());
        m_dao_person.delete(_person);
    }

    public void update(Person _person)
    {
        LOGGER.debug("Updating the following person: " + _person.getFirstname() + ", " + _person.getLastname());
    	m_dao_person.save(_person);
    }

    public List<Person> getAll()
    {
        LOGGER.debug(BOPerson.class.getName() + ": Getting all persons");

        return m_dao_person.getAll();
    }

    public Person getById(int _id)
    {
        return m_dao_person.getById(_id);
    }
}


  • File 'TestStruts2Spring3Hibernate4/Java Resources/main/org/tSprStrHib/action/ActionPerson'
package org.tSprStrHib.action;

import java.util.List;
import org.apache.log4j.Logger;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.Preparable;
import org.tSprStrHib.entity.Person;
import org.tSprStrHib.domain.BOPerson;

public class ActionPerson implements Preparable
{
    private static final Logger LOGGER = Logger.getLogger(ActionPerson.class.getName());

    private BOPerson m_bo_person;
    public void setBOPerson(BOPerson _bo_person) { this.m_bo_person = _bo_person; }

    private List<Person> m_persons;
    public List<Person> getPersons() { return m_persons; }

    private int m_id;
    public int getId() { return m_id; }
    public void setId(int _id) { m_id = _id; }

    private String m_firstname;
    public String getFirstname() { return m_firstname; }
    public void setFirstname(String _firstname) { m_firstname = _firstname; }

    private String m_lastname;
    public String getLastname() { return m_lastname; }
    public void setLastname(String _lastname) { m_lastname = _lastname; }

    public void prepare() throws Exception
    {
    }

    public String execute()
    {
        return Action.SUCCESS;
    }

    public String listAll()
    {
        LOGGER.debug("Get all persons");
        m_persons = m_bo_person.getAll();
        LOGGER.debug("Number of persons: " + m_persons.size());

        return Action.SUCCESS;
    }

    public String delete()
    {
        Person person = m_bo_person.getById(m_id);
        LOGGER.debug("Delete person " + person.getFirstname() + " with id " + person.getId());
        m_bo_person.delete(person);

        return Action.SUCCESS;
    }

    public String add()
    {
    	Person person = new Person();
    	person.setFirstname(m_firstname);
    	person.setLastname(m_lastname);
        LOGGER.debug("Add person: " + person.getFirstname());
        m_bo_person.add(person);

        return Action.SUCCESS;
    }
}


Create database and user

mysql -h 127.0.0.1 -u root
mysql> CREATE USER 'tSprStrHib' IDENTIFIED BY 'tSprStrHib';
mysql> CREATE DATABASE tSprStrHib CHARACTER SET 'utf8';
mysql> GRANT ALL PRIVILEGES ON tSprStrHib.* TO 'tSprStrHib' WITH GRANT OPTION;
mysql> FLUSH PRIVILEGES;
mysql> \q


Test the example project

mvn tomcat:run


References


Links