Struts 2 + Spring + Hibernate 开发流程
Struts 2 开发流程
第 1 步 在web.xml
中定义核心Filter来拦截用户请求
<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>
第 2 步 如果需要以POST方式提交请求,则定义包含表单数据的JSP页面。如果仅仅只是以GET方式发送请求,则无须经过这一步
第 3 步 定义处理用户请求的Action类
public class LoginAction extends ActionSupport {
private String username;
private String password;
private String tip;
/* getter & setter */
@Override
public String execute() {
ActionContext ctx = ActionContext.getContext();
Integer counter = (Integer) ctx.getApplication().get("counter");
if (counter == null) counter = 1;
else counter = counter + 1;
ctx.getApplication().put("counter", counter);
ctx.getSession().put("user", getUsername());
if (getUsername().equals("Tom") && getPassword().equals("123456")) {
ctx.put("tip", "登录成功");
return SUCCESS;
} else {
ctx.put("tip", "登录失败");
return ERROR;
}
}
}
第 4 步 在struts.xml
中配置Action
<package name="some" extends="struts-default">
<action name="login" class="com.duan.action.LoginAction">
<result name="success">/welcome.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
第 5 步 在struts.xml中配置处理结果和物理视图资源之间的对应关系
同上
第 6 步 编写视图资源
welcome.jsp
<html>
<head></head>
<body>
本站访问次数为:${applicationScope.counter} <br/>
${sessionScope.user},您已经登录! <br/>
${requestScope.tip} <br/>
</body>
</html>
Hibernate 开发流程
第 0 步 配置文件
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<property name="show_sql">true</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.min_size">1</property>
<property name="hibernate.c3p0.timeout">5000</property>
<property name="hibermate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="hibernate.c3p0.validate">true</property>
<mapping class="com.duan.entity.User"/>
</session-factory>
</hibernate-configuration>
第 1 步 开发持久化类
User.java
@Entity
@Table( name = "user")
public class User {
@Id
@GeneratedValue
private long id;
private String username;
private String password;
public User() {}
public User(String name, String pass) {
username = name;
password = pass;
}
/* getter & setter */
}
第 2 步 注册服务
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
第 3 步 获取SessionFactory
sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
第 4 步 获取Session,打开事务
Session session = sessionFactory.openSession();
session.beginTransaction();
第 5 步 用面向对象的方式操作数据库
session.save(new User("Tom", "123456"));
第 6 步 关闭事务,关闭Session
session.getTransaction().commit();
session.close();
Spring整合Struts 2
第 1 步 启动Spring容器
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
第 2 步 让Spring管理控制器
LoginAction.java
public class LoginAction extends ActionSupport {
...
private ConsumerService service;
public void setService(ConsumerService service) {
this.service = service;
}
...
}
struts.xml
<action name="login" class="loginAction">
...
</action>
applicationContext.xml
<bean id="service" class="com.duan.service.impl.ConsumerServiceImpl"/>
<bean id="loginAction" class="com.duan.action.LoginAction" scope="prototype">
<property name="service" ref="service"/>
</bean>
Spring整合Hibernate
第 1 步 管理SessionFactory
<!-- 定义数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/>
<property name="user" value="duan"/>
<property name="password" value="123456"/>
<property name="maxPoolSize" value="40"/>
<property name="minPoolSize" value="1"/>
<property name="initialPoolSize" value="1"/>
<property name="maxIdleTime" value="20"/>
</bean>
<!-- 定义SessionFactory-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
第 2 步 继承自HibernateDaoSupport的DaoImpl类
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
@Override
public User update(User user) {
getHibernateTemplate().update(user);
}
...
}
第 3 步 装配到应用上下文中
<bean id="userDao" class="com.duan.dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
第 4 步 用Spring管理事务
<!-- 事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 注解驱动事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
UserServiceImpl.java
@Transactional(propagation=Propagation.SUPPORTS)
@Reposity
public class UserServiceImpl implements UserService {
private UserDao userDao;
@Transactional(propagation=Propagation.REQUIRED)
@Override
public void modify(User user) {
userDao.update(user);
}
...
}