最近在试着接触maven,感觉用maven来部署项目比以前方便了许多;
废话不多说,现在就开始maven搭建struts2+hibernate3+spring3的框架吧;
我的项目中用的是eclipse,下面是项目的结构图
1、编写pom.xml添加项目需要的依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.clf</groupId>
<artifactId>div</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.12</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.4.Final</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.24</version>
</dependency>
<dependency>
<groupId>com.googlecode.sli4j</groupId>
<artifactId>sli4j-slf4j</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.3.12</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>2.3.12</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
</project>
2、接着我们web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>div</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<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>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
3、strut.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<constant name="struts.i18n.encoding" value="utf-8" />
<constant name="struts.convention.result.path" value="/WEB-INF/pages/" />
</struts>
4、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" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config />
<context:component-scan base-package="com.clf.dao" />
<context:component-scan base-package="com.clf.service" />
<context:property-placeholder location="classpath:jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driverClassName}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${username}"></property>
<property name="password" value="${password}"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.clf.entity</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=true
</value>
</property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
</beans>
driverClassName=org.gjt.mm.mysql.Driver
url=jdbc:mysql://localhost:3306/div
username=root
password=123456
6、log4j.properties
log4j.rootLogger=WARN,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d%p[%c]-%m%n
7、mysql数据库脚本:
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`USERNAME` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`PASSWORD` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'clf', 'clf');
下面介绍com.clf.utils包下的BaseEntity.java,ReflectionUtils.java,SimpleHibernateDao.java
BaseEntity.java
/**
*
*/
package com.clf.utils;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
/**
* @author chenlf
* @CreateTime : 2013-4-3 上午11:07:18
* @Description : XXX
*/
@MappedSuperclass
public class BaseEntity implements Serializable {
/**
*
*/
private static final long serialVersionUID = 6805535043573259672L;
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(Long id) {
this.id = id;
}
}
ReflectionUtils.java
/**
*
*/
package com.clf.utils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
/**
* @author chenlf
* @CreateTime : 2013-4-3 上午11:19:10
* @Description : XXX
*/
public class ReflectionUtils {
private static Logger logger = LoggerFactory.getLogger(ReflectionUtils.class);
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> Class<T> getSuperClassGenricType(final Class clazz) {
return getSuperClassGenricType(clazz, 0);
}
@SuppressWarnings("rawtypes")
public static Class getSuperClassGenricType(Class clazz, int index) {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " + params.length);
return Object.class;
}
if (!(params[index] instanceof Class)) {
logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
return Object.class;
}
return (Class) params[index];
}
public static Object getFieldValue(Object obj, String fieldName) {
Field field = getAccessibleField(obj, fieldName);
if (field == null) {
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
}
Object result = null;
try {
result = field.get(obj);
} catch (IllegalAccessException e) {
logger.error("impossible exception {}", e.getMessage());
}
return result;
}
private static Field getAccessibleField(Object obj, String fieldName) {
Assert.notNull(obj, "object can not be null!");
Assert.hasText(fieldName, "fieldName");
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
try {
Field field = superClass.getDeclaredField(fieldName);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {
}
}
return null;
}
@SuppressWarnings("rawtypes")
public static void setFieldValue(Object obj, String fieldName, List value) {
Field field = getAccessibleField(obj, fieldName);
if (field == null) {
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
}
try {
field.set(obj, value);
} catch (IllegalAccessException e) {
logger.error("impossible exception {}", e.getMessage());
}
}
public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException || e instanceof NoSuchMethodException) {
return new IllegalArgumentException("Reflection Exception.", e);
} else if (e instanceof InvocationTargetException) {
return new RuntimeException("Reflection Exception.", ((InvocationTargetException) e).getTargetException());
} else if (e instanceof RuntimeException) {
return (RuntimeException) e;
}
return new RuntimeException("Unexpected Checked Exception.", e);
}
}
SimpleHibernateDao.java
/**
*
*/
package com.clf.utils;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.metadata.ClassMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
/**
* @author chenlf
* @CreateTime : 2013-4-3 上午11:12:39
* @Description : XXX
*/
public class SimpleHibernateDao<T, ID extends Serializable> {
private Logger logger = LoggerFactory.getLogger(getClass());
protected SessionFactory sessionFactory;
protected Class<T> entityClass;
public SimpleHibernateDao() {
this.entityClass = ReflectionUtils.getSuperClassGenricType(getClass());
}
public SimpleHibernateDao(final SessionFactory sessionFactory, final Class<T> entityClass) {
this.sessionFactory = sessionFactory;
this.entityClass = entityClass;
}
/**
* @return the sessionFactory
*/
public SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* @param sessionFactory
* the sessionFactory to set
*/
@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getSession() {
return this.getSessionFactory().getCurrentSession();
}
public void save(final T entity) {
Assert.notNull(entity, "entity can not be null!");
this.getSession().saveOrUpdate(entity);
logger.debug("save entity {}", entity);
}
public void delete(final T entity) {
Assert.notNull(entity, "entity can not be null!");
this.getSession().delete(entity);
logger.debug("delete entity {}", entity);
}
public void delete(final ID id) {
Assert.notNull(id, "id can not be null!");
this.delete(get(id));
logger.debug("delete entity {},id is {}", entityClass.getSimpleName(), id);
}
@SuppressWarnings("unchecked")
public T get(ID id) {
Assert.notNull(id, "id can not be null!");
return (T) this.getSession().get(entityClass, id);
}
public List<T> get(final Collection<ID> ids) {
return find(Restrictions.in(getIdName(), ids));
}
public List<T> getAll() {
return find();
}
@SuppressWarnings("unchecked")
public List<T> getAll(String orderByProperty, boolean isAsc) {
Criteria c = createCriteria();
if (isAsc) {
c.addOrder(Order.asc(orderByProperty));
} else {
c.addOrder(Order.desc(orderByProperty));
}
return c.list();
}
public List<T> findBy(final String propertyName, final Object value) {
Assert.hasText(propertyName, "propertyName can not be null!");
Criterion criterion = Restrictions.eq(propertyName, value);
return find(criterion);
}
@SuppressWarnings("unchecked")
public T findUniqueBy(final String propertyName, final Object value) {
Assert.hasText(propertyName, "propertyName can not be null!");
Criterion criterion = Restrictions.eq(propertyName, value);
return (T) createCriteria(criterion).uniqueResult();
}
@SuppressWarnings("unchecked")
public <X> List<X> find(final String hql, final Object... values) {
return createQuery(hql, values).list();
}
@SuppressWarnings("unchecked")
public <X> List<X> find(int limit, final String hql, final Object... values) {
if (limit == 0) {
limit = 1;
}
Query query = createQuery(hql, values);
query.setFirstResult(0);
query.setMaxResults(limit);
return query.list();
}
@SuppressWarnings("unchecked")
public <X> List<X> find(final String hql, final Map<String, ?> values) {
return createQuery(hql, values).list();
}
@SuppressWarnings("unchecked")
public <X> X findUnique(final String hql, final Object... values) {
return (X) createQuery(hql, values).uniqueResult();
}
@SuppressWarnings("unchecked")
public <X> X findUnique(final String hql, final Map<String, ?> values) {
return (X) createQuery(hql, values).uniqueResult();
}
public int batchExecute(final String hql, final Object... values) {
return createQuery(hql, values).executeUpdate();
}
public int batchExecute(final String hql, final Map<String, ?> values) {
return createQuery(hql, values).executeUpdate();
}
public Query createQuery(final String queryString, final Object... values) {
Assert.hasText(queryString, "queryString can not be null!");
Query query = getSession().createQuery(queryString);
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
return query;
}
public Query createQuery(final String queryString, final Map<String, ?> values) {
Assert.hasText(queryString, "queryString can not be null!");
Query query = getSession().createQuery(queryString);
if (values != null) {
query.setProperties(values);
}
return query;
}
@SuppressWarnings("unchecked")
public List<T> find(final Criterion... criterions) {
return createCriteria(criterions).list();
}
@SuppressWarnings("unchecked")
public T findUnique(final Criterion... criterions) {
return (T) createCriteria(criterions).uniqueResult();
}
public Criteria createCriteria(final Criterion... criterions) {
Criteria criteria = getSession().createCriteria(entityClass);
for (Criterion c : criterions) {
criteria.add(c);
}
return criteria;
}
public void initProxyObject(Object proxy) {
Hibernate.initialize(proxy);
}
public void flush() {
getSession().flush();
}
public Query distinct(Query query) {
query.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
return query;
}
public Criteria distinct(Criteria criteria) {
criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
return criteria;
}
public String getIdName() {
ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass);
return meta.getIdentifierPropertyName();
}
public boolean isPropertyUnique(final String propertyName, final Object newValue, final Object oldValue) {
if (newValue == null || newValue.equals(oldValue)) {
return true;
}
Object object = findUniqueBy(propertyName, newValue);
return (object == null);
}
}
com.clf.entity包下的User.java
/**
*
*/
package com.clf.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.clf.utils.BaseEntity;
/**
* @author chenlf
* @CreateTime : 2013-4-3 上午11:06:25
* @Description : XXX
*/
@Entity
@Table
public class User extends BaseEntity {
/**
*
*/
private static final long serialVersionUID = -378435596254853899L;
@Column(name = "USERNAME")
private String userName;
@Column(name = "PASSWORD")
private String userPwd;
/**
* @return the userName
*/
public String getUserName() {
return userName;
}
/**
* @param userName
* the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return the userPwd
*/
public String getUserPwd() {
return userPwd;
}
/**
* @param userPwd
* the userPwd to set
*/
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
}
com.clf.dao包下的UserDao.java
/**
*
*/
package com.clf.dao;
import org.springframework.stereotype.Repository;
import com.clf.entity.User;
import com.clf.utils.SimpleHibernateDao;
/**
* @author chenlf
* @CreateTime : 2013-4-3 上午11:21:53
* @Description : XXX
*/
@Repository
public class UserDao extends SimpleHibernateDao<User, Long> {
}
com.clf.action包下的IndexAction.java, LoginAction.java
IndexAction.java
/**
*
*/
package com.clf.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
/**
* @author chenlf
* @CreateTime : 2013-4-3 上午10:05:27
* @Description : XXX
*/
public class IndexAction {
@Action(value = "/toLogin", results = { @Result(name = "login", location = "login.jsp") })
public String toLogin() {
return "login";
}
}
LoginAction.java
/**
*
*/
package com.clf.action;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import com.clf.action.form.UserForm;
import com.clf.service.UserService;
import com.opensymphony.xwork2.ModelDriven;
/**
* @author chenlf
* @CreateTime : 2013-4-3 上午9:57:00
* @Description : XXX
*/
public class LoginAction implements ModelDriven<UserForm> {
@Autowired
private UserService userService;
private UserForm form;
@Action(value = "/login", results = { @Result(name = "error", location = "error.jsp"),
@Result(name = "success", location = "welcome.jsp") })
public String login() {
Map<String, Object> map = userService.login(form);
HttpServletRequest request = ServletActionContext.getRequest();
request.setAttribute("user", map.get("user"));
if ((Boolean) map.get("result")) {
return "success";
} else {
return "error";
}
}
/*
* (non-Javadoc)
*
* @see com.opensymphony.xwork2.ModelDriven#getModel()
*/
public UserForm getModel() {
form = new UserForm();
return form;
}
}
com.clf.action.form包下的UserForm.java
/**
*
*/
package com.clf.action.form;
/**
* @author chenlf
* @CreateTime : 2013-4-3 上午10:28:51
* @Description : XXX
*/
public class UserForm {
private String userName;
private String userPwd;
/**
* @return the userName
*/
public String getUserName() {
return userName;
}
/**
* @param userName
* the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return the userPwd
*/
public String getUserPwd() {
return userPwd;
}
/**
* @param userPwd
* the userPwd to set
*/
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
}
这里做一下解释,由于自己研究的,就没有严格的用面向接口来设计项目。
有需要的源代码的可以到下面地址下载: