返回列表 发帖

[原创] [原创]Struts2+Spring+Hibernate整合

由于struts2目前还没有插件可以支持Eclipse,因此需要手工配制。我们先在eclipse下创建一个web project命名为SSHDemo
然后我们下载这3个框架来配制我们所需要的开发环境。下图显示所需要的lib

第一步,在web.xml中配置struts2spring
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
第二步,在spring的配置文件applicationContext.xml中配置数据源
    <!-- 定义数据源Bean,使用C3P0数据源实现 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
       <!-- 指定连接数据库的驱动 -->
       <property name="driverClass" value="com.mysql.jdbc.Driver"/>
       <!-- 指定连接数据库的URL -->
       <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/sshdemo"/>
       <!-- 指定连接数据库的用户名 -->
       <property name="user" value="root"/>
       <!-- 指定连接数据库的密码 -->
       <property name="password" value="715523715"/>
       <!-- 指定连接数据库连接池的最大连接数 -->
       <property name="maxPoolSize" value="20"/>
       <!-- 指定连接数据库连接池的最小连接数 -->
       <property name="minPoolSize" value="1"/>
       <!-- 指定连接数据库连接池的初始化连接数 -->
       <property name="initialPoolSize" value="1"/>
       <!-- 指定连接数据库连接池的连接的最大空闲时间 -->
       <property name="maxIdleTime" value="20"/>
   </bean>
第三步,开始编码,下图显示项目的是包的结构

创建一个User
public class User implements Serializable{
    private int id;
    private String user;
    private String pass;
    private String email;
    
    public int getId() {
       return id;
    }
    public void setId(int id) {
       this.id = id;
    }
    public String getUser() {
       return user;
    }
    public void setUser(String user) {
       this.user = user;
    }
    public String getPass() {
       return pass;
    }
    public void setPass(String pass) {
       this.pass = pass;
    }
    public String getEmail() {
       return email;
    }
    public void setEmail(String email) {
       this.email = email;
    }  
}
User.hbm.xml就省略了。

在applicationContext.xml中配置sessionFactory
    <!--定义了Hibernate的SessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mappingResources">
            <list>
              <value>com/hopeteam/model/User.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.jdbc.batch_size">20</prop>
            </props>
        </property>
    </bean>
创建Dao
public interface UserDao {
    /**
     * 根据id查找用户
     * @param id 需要查找的种类id
     */  
    User get(int id);
    /**
     * 增加种类
     * @param user 需要增加的种类
     */      
    void save(User user);

    /**
     * 修改用户
     * @param user 需要修改的用户
     */  
    void update(User user);

    /**
     * 删除用户
     * @param id 需要删除的用户id
     */  
    void delete(int id);

    /**
     * 删除用户
     * @param user 需要删除的用户
     */  
    void delete(User user);

    /**
     * 查询全部用户
     * @return 获得全部用户
     */
    List<User> findAll();

    /**
     * 根据用户名,密码查找用户
     * @param user 查询所需的用户名
     * @param pass 查询所需的密码
     * @return 对应的用户
     */
    User findUserByNameAndPass(String user , String pass);

    /**
     * 根据用户名查找用户
     * @param user 查询所需的用户名
     * @return 对应的用户
     */
    User findUserByName(String user);
}
创建Service
public interface UserService {
    /**
     * 新增用户
     * @param user 新增用户的用户名
     * @param pass 新增用户的密码
     * @param email 新增用户的电子邮件
     * @return 新增用户的主键
     */
    int addUser(String user , String pass , String email)
       throws Exception;

    /**
     * 验证用户登陆
     * @param user 需要登陆的用户名
     * @param pass 需要登陆的密码
     * @return 是否登陆成功
     */
    int loginValid(String user , String pass)
       throws Exception;

}

创建Action:LoginAction和RegistAction
public class LoginAction extends ActionSupport {
    private String user;
    private String pass;
    private UserService us;
    
    public void setUs(UserService us)
    {
        this.us = us;
    }

    @Override
    public String execute() throws Exception
    {
       Map session = ActionContext.getContext().getSession();

        int userId = us.loginValid(user, pass);
       if (userId > 0) {
           session.put("userId", userId);
           return SUCCESS;
       } else {
           addActionError("用户名/密码不匹配");
       }


       return "failure";
    }

    public void setUser(String user)
    {
       this.user = user;
    }
    public String getUser()
    {
        return this.user;
    }

    public void setPass(String pass)
    {
       this.pass = pass;
    }
    public String getPass()
    {
        return this.pass;
    }
    
}


public class RegistAction extends ActionSupport{
    private String user;
    private String pass;
    private String email;
    private UserService us;

    public void setUs(UserService us)
    {
        this.us = us;
    }
    
    @Override
    public String execute() throws Exception
    {
       Map session = ActionContext.getContext().getSession();


       if (us.addUser(user, pass, email) > 0) {
           return SUCCESS;
       } else {
           addActionError("注册失败,请重试!");
           return "failure";
       }
    }


    public void setUser(String user)
    {
       this.user = user;
    }
    public String getUser()
    {
        return this.user;
    }

    public void setPass(String pass)
    {
       this.pass = pass;
    }
    public String getPass()
    {
        return this.pass;
    }

    public void setEmail(String email)
    {
       this.email = email;
    }
    public String getEmail()
    {
        return this.email;
    }

}

第四步:配置struts.xml中的actionapplicationContxt.xml中的bean
Struts.xml

<struts>
    <include file ="struts-default.xml"/>
    
    <constant name="struts.i18n.encoding" value="GBK"/>
    <constant name="struts.objectFactory" value="spring"/>
    
    <package name="fengzhizi" extends="struts-default">

       <global-results>
           <!-- 下面定义的结果对所有的Action都有效 -->
           <result name="exception">/error.jsp</result>
           <result name="success">/success.jsp</result>
        </global-results>

        <global-exception-mappings>
           <!-- 指Action抛出Exception异常时,转入名为exception的结果。 -->
           <exception-mapping exception="java.lang.Exception" result="exception"/>
       </global-exception-mappings>

       <action name="Regist" class="com.hopeteam.struts.actions.RegistAction">
           <result name="failure">/Regist.jsp</result>
        </action>

       <action name="Login" class="com.hopeteam.struts.actions.LoginAction">
           <result name="failure">/Login.jsp</result>
        </action>

    </package>

</struts>

applicationContext.xml中的事务处理,和servicedao bean的配置
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
        <!--  事务拦截器bean需要依赖注入一个事务管理器 -->
        <property name="transactionManager" ref="transactionManager"/>
    <property name="transactionAttributes">
           <!--  下面定义事务传播属性-->
           <props>
               <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
           <prop key="*">PROPAGATION_REQUIRED</prop>
           </props>
        </property>
    </bean>

    <!-- 定义BeanNameAutoProxyCreator-->
    <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
        <!--  指定对满足哪些bean name的bean自动生成业务代理 -->
        <property name="beanNames">
             <value>us</value>
        </property>
        <!--  下面定义BeanNameAutoProxyCreator所需的事务拦截器-->
        <property name="interceptorNames">
            <list>
                <!-- 此处可增加其他新的Interceptor -->
                <value>transactionInterceptor</value>
            </list>
        </property>
    </bean>
    <bean id="us" class="com.hopeteam.service.impl.UserServiceImpl">
         <property name="userDao" ref="userDao"/>
    </bean>

    <bean id="userDao" class="com.hopeteam.dao.impl.UserDaoImpl">
       <property name="sessionFactory" ref="sessionFactory"/>
</bean>

第五步,编写jsp,然后部署web工程
给出截图吧,jsp页面就省略了

附件:
天行健,君子以自强不息
地势坤,君子以厚德载物
   黑色海岸线欢迎您

返回列表 回复 发帖