五、 添加注解配置
1. 修改struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<!-- 开启使用开发模式,详细错误提示 -->
<constant name="struts.devMode" value="true" />
<!-- 将对象交给spring管理 -->
<constant name="struts.objectFactory" value="spring" />
<!-- 指定资源编码类型 -->
<constant name="struts.i18n.encoding" value="UTF-8" />
<!-- 指定每次请求到达,重新加载资源文件 -->
<constant name="struts.i18n.reload" value="true" />
<!-- 指定每次配置文件更改后,自动重新加载 -->
<constant name="struts.configuration.xml.reload" value="false" />
<!-- 国际化资源文件 -->
<constant name="struts.custom.i18n.resources" value="content/Language" />
<!-- 浏览器缓存 -->
<constant name="struts.serve.static.browserCache" value="false" />
<!-- 默认后缀名 -->
<constant name="struts.action.extension" value="do,action,jhtml,," />
<!-- Struts Annotation -->
<constant name="actionPackages" value="com.frank.action" />
</struts>
2. 修改LoginAction,在execute方法上添加
@Action(value = "login", results = {
@Result(name = INPUT, location = "/index.jsp"),
@Result(name = SUCCESS, location = "/WEB-INF/content/success.jsp") })
3. action注解完成,可以测试通过,接下来添加service注解等
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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd ">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver">
</property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="admin"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.frank.model.Student</value>
</list>
</property>
</bean>
<!-- 使用 annotation 自动注册bean,并检查@Controller, @Service, @Repository注解已被注入 -->
<context:component-scan base-package="com.frank" />
</beans>
5. Service、dao 的接口和实现类
StudentService.java
public interface StudentService {
/**
* 根据主键查询Student
* @param id
* @return
*/
public Student findById(Integer id);
}
StudentServiceImpl.java
@Service
public class StudentServiceImpl implements StudentService {
@Resource
private StudentDAO studentDAO;
@Override
public Student findById(Integer id) {
// TODO Auto-generated method stub
return studentDAO.findById(id);
}
}
StudentDAO.java
public interface StudentDAO{
public abstract void save(Student transientInstance);
public abstract void delete(Student persistentInstance);
public abstract Student findById(java.lang.Integer id);
public abstract List<Student> findByExample(Student instance);
public abstract List findByProperty(String propertyName, Object value);
public abstract List<Student> findByName(Object name);
public abstract List findAll();
public abstract Student merge(Student detachedInstance);
public abstract void attachDirty(Student instance);
public abstract void attachClean(Student instance);
}
StudentDAOImpl.java
@Repository
public class StudentDAOImpl extends HibernateDaoSupport implements StudentDAO {
private static final Logger log = LoggerFactory
.getLogger(StudentDAOImpl.class);
// property constants
public static final String NAME = "name";
private SessionFactory sessionFacotry;
@Resource
public void setSessionFacotry(SessionFactory sessionFacotry) {
super.setSessionFactory(sessionFacotry);
}
protected void initDao() {
// do nothing
}
/*
* (non-Javadoc)
*
* @see com.frank.dao.impl.S#save(com.frank.model.Student)
*/
@Override
public void save(Student transientInstance) {
log.debug("saving Student instance");
try {
getHibernateTemplate().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
/*
* (non-Javadoc)
*
* @see com.frank.dao.impl.S#delete(com.frank.model.Student)
*/
@Override
public void delete(Student persistentInstance) {
log.debug("deleting Student instance");
try {
getHibernateTemplate().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
/*
* (non-Javadoc)
*
* @see com.frank.dao.impl.S#findById(java.lang.Integer)
*/
@Override
public Student findById(java.lang.Integer id) {
log.debug("getting Student instance with id: " + id);
try {
Student instance = (Student) getHibernateTemplate().get(
"com.frank.model.Student", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
/*
* (non-Javadoc)
*
* @see com.frank.dao.impl.S#findByExample(com.frank.model.Student)
*/
@Override
public List<Student> findByExample(Student instance) {
log.debug("finding Student instance by example");
try {
List<Student> results = (List<Student>) getHibernateTemplate()
.findByExample(instance);
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
/*
* (non-Javadoc)
*
* @see com.frank.dao.impl.S#findByProperty(java.lang.String,
* java.lang.Object)
*/
@Override
public List findByProperty(String propertyName, Object value) {
log.debug("finding Student instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from Student as model where model."
+ propertyName + "= ?";
return getHibernateTemplate().find(queryString, value);
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
/*
* (non-Javadoc)
*
* @see com.frank.dao.impl.S#findByName(java.lang.Object)
*/
@Override
public List<Student> findByName(Object name) {
return findByProperty(NAME, name);
}
/*
* (non-Javadoc)
*
* @see com.frank.dao.impl.S#findAll()
*/
@Override
public List findAll() {
log.debug("finding all Student instances");
try {
String queryString = "from Student";
return getHibernateTemplate().find(queryString);
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
/*
* (non-Javadoc)
*
* @see com.frank.dao.impl.S#merge(com.frank.model.Student)
*/
@Override
public Student merge(Student detachedInstance) {
log.debug("merging Student instance");
try {
Student result = (Student) getHibernateTemplate().merge(
detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
/*
* (non-Javadoc)
*
* @see com.frank.dao.impl.S#attachDirty(com.frank.model.Student)
*/
@Override
public void attachDirty(Student instance) {
log.debug("attaching dirty Student instance");
try {
getHibernateTemplate().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
/*
* (non-Javadoc)
*
* @see com.frank.dao.impl.S#attachClean(com.frank.model.Student)
*/
@Override
public void attachClean(Student instance) {
log.debug("attaching clean Student instance");
try {
getHibernateTemplate().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
六、 附加功能完善
1. 添加log日志输出
log4j.rootLogger=WARN, console, logFile
#Console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d %p [%c] - <%m>%n
#RollingFile
log4j.appender.logFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logFile.File=../logs/king.log
log4j.appender.logFile.layout=org.apache.log4j.PatternLayout
log4j.appender.logFile.layout.ConversionPattern=%d %p [%c] - <%m>%n
2. 添加编码转换web.xml
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3. 实体类配置修改
<property name="annotatedClasses">
<list>
<value>com.frank.model.Student</value>
</list>
</property>
修改为
<property name="packagesToScan" value="com.*.model" />
4. 数据源添加连接池信息
<!-- Connection Pooling Info -->
<property name="initialSize" value="5" />
<property name="maxActive" value="100" />
<property name="maxIdle" value="30" />
<property name="maxWait" value="500" />
<property name="defaultAutoCommit" value="false" />
5. 添加事务和aop支持
<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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
6. 配置事务管理
<!-- 配置事务管理 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 配置注解实现管理事务(cglib:proxy-target-class="true") -->
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="true" />
七、 到此,项目搭建已完成,自己可以做一下其它方面的优化和配置,接下来可以做自己喜欢的项目开发了。
文章看了别人的,修改了下,文章可能说的不够清楚,大家可以直接下载源码查看下就明白了: