Structs+Spring+Hibernate,這是很經典的一個搭配,它的開發流程也比較程式化,下面以用戶註冊爲例。
註冊頁面代碼:html
<%@page contentType="text/html;charset=GBK"%>
<html>
<head><title>Spring、Struts和Hibernate整合之用戶註冊</title></head>
<body>${msg}
<form name="user" action="/myHibernate/regedit.do" method="post">
用戶名 <input type="text" name="username" value="${user.username}"/><br>
密 碼 <input type="password" name="password" value="${user.password}"/><br>
<input type="submit" name="method" value="提交"/>
</form>
</body>
</html>
實體Bean類:java
package com.myHibernate.bean;
public class User1 {
// 定義id
private String id = null;
//定義用戶名
private String username = null;
//定義密碼
private String password = null;
//設定id
public void setId(String id) {
this.id = id;
}
//獲取id
public String getId() {
return this.id;
}
//設定用戶名
public void setUsername (String username) {
this.username = username;
}
//獲取用戶名
public String getUsername () {
return this.username;
}
//設定密碼
public void setPassword (String password) {
this.password = password;
}
//獲取密碼
public String getPassword () {
return this.password;
}
}
對應的映射文件User.hbm.xml:mysql
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.myHibernate.bean">
<class name="User" table="user">
<!--定義id-->
<id name="id" column="id">
<generator class="native"/>
</id>
<!--定義用戶名-->
<property name="username"/>
<!--定義密碼-->
<property name="password"/>
</class>
</hibernate-mapping>
用戶DAO接口:web
package com.myHibernate.dao;
import com.myHibernate.bean.User;
public interface UserDAO {
//查詢用戶
public abstract User queryUser(String name);
//新增用戶
public abstract void insertUser(User user);
//修改用戶
public abstract void updateUser(User user);
//刪除用戶
public abstract void deleteUser(User user);
}
用戶DAO接口實現類:spring
package com.myHibernate.dao.impl;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.myHibernate.bean.User;
import com.myHibernate.dao.UserDAO;
public class UserDAOImpl extends HibernateDaoSupport implements UserDAO{
private SessionFactory sessionFactory;
private String hql = "from User u where u.username = ?";
//查詢用戶
public User queryUser(String name) {
User user = null;
//若是查詢結果爲空
if (this.getHibernateTemplate().find(hql, name) == null ) {
user = null;
} else {
//不爲空時,取第一筆
user = (User)this.getHibernateTemplate().find(hql, name).get(0);
}
return user;
}
//新增用戶
public void insertUser(User user) {
this.getHibernateTemplate().save(user);
}
//修改用戶
public void updateUser(User user) {
this.getHibernateTemplate().update(user);
}
//刪除用戶
public void deleteUser(User user) {
this.getHibernateTemplate().delete(user);
}
}
註冊的業務邏輯接口:
sql
package com.myHibernate.domain;
import com.myHibernate.bean.User;
public interface Regedit {
//保存用戶
public abstract void saveUser(User user);
//修改用戶
public abstract void updateUser(User user);
//刪除用戶
public abstract void deleteUser(User user);
//獲取是否保存成功的消息
public abstract String getMsg();
}
註冊的業務邏輯實現:數據庫
package com.myHibernate.domain.impl;
import com.myHibernate.bean.User;
import com.myHibernate.dao.UserDAO;
import com.myHibernate.domain.Regedit;
public class RegeditImpl implements Regedit{
private String msg;
private UserDAO userDao;
//保存用戶
public void saveUser(User user) {
userDao.insertUser(user);
msg = "保存成功";
}
//修改用戶
public void updateUser(User user) {
userDao.updateUser(user);
}
//刪除用戶
public void deleteUser(User user) {
userDao.deleteUser(user);
}
//獲取是否保存成功的消息
public String getMsg() {
return msg;
}
/**
* @返回userDao
*/
public UserDAO getUserDao() {
return userDao;
}
/**
* @注入userDao
*/
public void setUserDao(UserDAO userDao) {
this.userDao = userDao;
}
}
用戶註冊控制器類:apache
package com.myHibernate.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//導入struts包
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.myHibernate.bean.User;
import com.myHibernate.domain.Regedit;
//繼承action
public class RegeditAction extends Action {
//定義接口Regedit
private Regedit regedit;
//獲取值
public Regedit getRegedit () {
return regedit;
}
//依賴注入值
public void setRegedit (Regedit regedit) {
this.regedit = regedit;
}
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
//獲取用戶提交的信息
User user = (User)form;
//保存用戶提交的信息
getRegedit().saveUser(user);
//將用戶提交的信息和是否保存成功的信息存放在request中
request.setAttribute("user", user);
request.setAttribute("msg", regedit.getMsg());
//返回頁面
return mapping.findForward("regedit");
}
}
下面是配置文件方面,首先是Hibernate的配置文件hibernate.cfg.xml,定義了訪問數據庫所須要的一些值:session
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/myHibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="com/myHibernate/bean/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
而後是Spring的配置文件spring-config.xml:
架構
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!--定義數據源-->
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<!--設定驅動-->
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<!--設定url-->
<property name="url">
<value>jdbc:mysql://localhost/myHibernate</value>
</property>
<!--設定用戶名-->
<property name="username">
<value>root</value>
</property>
</bean>
<!--經過org.springframework.orm.hibernate3.LocalSessionFactoryBean創建聯繫-->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref local="dataSource" />
</property>
<!--定義要使用的映射文件-->
<property name="mappingResources">
<list>
<value>com/myHibernate/bean/User.hbm.xml</value>
</list>
</property>
<!--定義要使用的方言和是否顯示sql-->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!--這裏添加對事務處理的支持,固然也能夠不用-->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<!--表示要將下面定義的userDao置於事務處理之下-->
<bean id="userDaoProxy"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<!--要代理userDao-->
<property name="target">
<ref local="userDao" />
</property>
<!--定義不一樣狀況下,事務處理的方式-->
<property name="transactionAttributes">
<props>
<prop key="create*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="query*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<!--定義userDao-->
<bean id="userDao" class="com.myHibernate.dao.impl.UserDAOImpl">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<!--定義regedit,將UserDAO進行注入-->
<bean id="regedit" class="com.myHibernate.domain.impl.RegeditImpl">
<property name="userDao">
<ref local="userDao" />
</property>
</bean>
<!--定義login,將UserDAO進行注入-->
<bean id="login" class="com.myHibernate.domain.impl.LoginImpl">
<property name="userDao">
<ref local="userDao" />
</property>
</bean>
<!--定義和Struts相應的映射,將regedit進行注入-->
<bean name="/regedit" class="com.myHibernate.action.RegeditAction">
<property name="regedit">
<ref bean="regedit"/>
</property>
</bean>
<!--定義和Struts相應的映射,將login進行注入-->
<bean name="/login" class="com.myHibernate.action.LoginAction">
<property name="login">
<ref bean="login"/>
</property>
</bean>
</beans>
而後是Struts的配置文件struts-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
<struts-config><!--定義formbean--><form-beans><form-bean name="user" type="com.myHibernate.bean.User"/></form-beans>
<action-mappings>
<!--定義和SPring配置文件相同的路徑-->
<action path="/regedit" type="org.springframework.web.struts.DelegatingActionProxy" name="user">
<forward name="regedit" path="/jsp/regedit.jsp"/>
</action>
<!--定義初次訪問時的路徑-->
<action path="/input"
type="org.apache.struts.actions.ForwardAction"
parameter="/jsp/regedit.jsp"/>
<!--定義和SPring配置文件相同的路徑-->
<action path="/login"
type="org.springframework.web.struts.DelegatingActionProxy" name="user">
<forward name="login" path="/jsp/login.jsp"/>
</action>
<!--定義初次訪問時的路徑-->
<action path="/loginTemp"
type="org.apache.struts.actions.ForwardAction"
parameter="/jsp/login.jsp"/>
</action-mappings>
<!--註冊ContextLoaderPlugIn插件-->
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation" value="/WEB-INF/spring-config.xml" />
</plug-in>
</struts-config>
最後是Web應用程序配置文件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">
<servlet>
<servlet-name>actionServlet</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<!--初始參數-->
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!--處理全部後綴爲do的請求-->
<servlet-mapping>
<servlet-name>actionServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
能夠看到,MVC的三層架構思路很清晰,但缺點也很明顯,配置文件太過於冗雜,CRUD代碼隨處冗餘,不夠簡約,下一篇文章中咱們將見識到一個解決這個問題的優秀框架—SpringSide。