Structs+Spring+Hibernate快速入门

Structs+Spring+Hibernate,这是很经典的一个搭配,它的开发流程也比较程式化,下面以用户注册为例。
    注册页面代码:

<%@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类:

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:

<?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接口:

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接口实现类:

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);

    }

}

注册的业务逻辑接口:


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;

    }

}

用户注册控制器类:

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,定义了访问数据库所需要的一些值:

<?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。

上一篇:LeetCode 789. Escape The Ghosts


下一篇:使用absolute布局