java 從零開始,學習筆記之基礎入門(四十二)

Hibernate-Spring-Struts

頁面部分(註冊和註冊成功)

註冊

Index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

   

    <title>My JSP 'index.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control" content="no-cache">

    <meta http-equiv="expires" content="0">   

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

    <meta http-equiv="description" content="This is my page">

    <!--

    <link rel="stylesheet" type="text/css" href="styles.css">

    -->

  </head>

 

  <body>

    用戶註冊

    <hr/>

    <form action="register.do" name="registerform" id="registerform" method="post">

    <br/>

    用戶ID:<input type="text" name="stu.userid" id="stu.userid"/>

               <br/>

    用戶名稱:<input type="text" name="stu.username" id="stu.username"/>

               <br/>

    用戶密碼:<input type="text" name="stu.pwd" id=stu.pwd/>

            <input type="submit" value="提交"/>

    </form>

  </body>

</html>

 

註冊成功

Success.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

   

    <title>My JSP 'success.jsp' starting page</title>

   

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control" content="no-cache">

    <meta http-equiv="expires" content="0">   

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

    <meta http-equiv="description" content="This is my page">

    <!--

    <link rel="stylesheet" type="text/css" href="styles.css">

    -->

 

  </head>

 

  <body>

    <a style="color:red;font:25px;">Struts-Spring-Hibernate整合成功</a>

  </body>

</html>

 

 

Web配置文件

Web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5"

    xmlns="http://java.sun.com/xml/ns/javaee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

  <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>

 

   <context-param>

    <param-name>contextConfigLocation</param-name>

    <param-value>classpath*:applicationContext-*.xml</param-value>

  </context-param>

 

  <listener>

    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

  </listener>

 

  <filter>

    <filter-name>filterDispatcher</filter-name>

    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>

  </filter>

 

  <filter-mapping>

    <filter-name>filterDispatcher</filter-name>

    <url-pattern>/*</url-pattern>

  </filter-mapping>

 

 

</web-app>

 

 

全局屬性文件的配置

Struts.properties

struts.action.extension=do

 

struts.objectFactory=spring

 

struts.objectFactory.spring.autowire=name

 

Struts配置文件

Struts.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC

    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <package name="user" extends="struts-default">

       <action name="register" class="useraction">

           <result name="success">success.jsp</result>

           <result name="fail">fail.jsp</result>

       </action>

    </package>

</struts>

 

Spring核心配置文件

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"

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 

    <import resource="applicationContext-dao.xml"/>

   

    <import resource="applicationContext-tran.xml"/>

   

    <import resource="applicationContext-service.xml"/>

   

    <import resource="applicationContext-action.xml"/>

 

</beans>

 

Spring節點配置文件()

ApplicationContext-action.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"

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

   

    <bean id="useraction" class="com.ibm.action.UserManagerAction">

    <property name="service" ref="useroperservice"></property>

    </bean>

</beans>

Spring節點配置文件()

applicationContext-service.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"

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 

    <bean id="useroperservice" class="com.ibm.service.iservice.UserOperService">

    <property name="userOperDAO" ref="userdao"></property>

    </bean>

   

</beans>

Spring節點配置文件()

applicationContext-dao.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"

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 

    <bean id="userdao" class="com.ibm.dao.idao.UserOperDAO">

    <property name="sessionFactory" ref="sessionFactory"></property>

    </bean>

   

</beans>

Spring節點配置文件()

applicationContext-tran.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:aop="http://www.springframework.org/schema/aop"  

    xmlns:tx="http://www.springframework.org/schema/tx"

   

    xsi:schemaLocation="

    http://www.springframework.org/schema/aop

    http://www.springframework.org/schema/aop/spring-aop-2.5.xsd

    http://www.springframework.org/schema/beans

    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

    http://www.springframework.org/schema/tx

    http://www.springframework.org/schema/tx/spring-tx-2.5.xsd

    ">

   

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

       <property name="configLocation"

           value="classpath:hibernate.cfg.xml">

       </property>

    </bean>

   

    <!-- 管理上面配置的SessionFactory -->

    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">

       <!-- "sessionFactory"HibernateTransactionManager類的屬性名,必須這麼寫 -->

       <property name="sessionFactory" ref="sessionFactory"></property>

       <!-- 上面的"ref"指定需要管理事務的SessionFactory,即上面配置的 -->

   

    </bean>

   

<!--以下兩個配置節點用來  -->

    <!-- 配置事務的傳播屬性 -->

    <tx:advice id="tx" transaction-manager="transactionManager">

        <tx:attributes>

             <tx:method name="add*" propagation="REQUIRED"/>

             <tx:method name="del*" propagation="REQUIRED"/>

             <tx:method name="update*" propagation="REQUIRED"/>

           <!-- 找不到以上的方法則所有操作都默認執行下面這個方法,即以只讀的方式操作(可以做""的操作) -->

             <tx:method name="*" read-only="true"/>

        </tx:attributes>

    </tx:advice>

   

    <!-- 切面(AOP)配置 -->

    <aop:config>

       <aop:pointcut expression="execution (* com.ibm.service.*.*(..))" id="aid"/>

       <!--

                           定義通知者(即advisor,它與aspect一樣,它是由PointcutAdvice組成的),一般用於事務的配置

             * pointcut-ref:指定要使用的Pointcut,這裏指定id即可

             * advice-ref:指定Advice,這裏指定id即可

             * <aop:advisor>的含義就是將哪個Advice應用到約定的範圍(即Pointcut指定的)上去

        -->

       <aop:advisor advice-ref="tx" pointcut-ref="aid"/>

    </aop:config>

   

    </beans>

 

 

 

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">

 

<!-- Generated by MyEclipse Hibernate Tools.                   -->

<hibernate-configuration>

 

    <session-factory>

       <property name="dialect">

           org.hibernate.dialect.SQLServerDialect

       </property>

       <property name="connection.url">

           jdbc:sqlserver://localhost:1433;databaseName=ibm001

       </property>

       <property name="connection.username">sa</property>

       <property name="connection.password">123</property>

       <property name="connection.driver_class">

           com.microsoft.sqlserver.jdbc.SQLServerDriver

       </property>

       <property name="myeclipse.connection.profile">sqlconn</property>

       <property name="format_sql">true</property>

       <property name="show_sql">true</property>

      

       <!-- 

       <property name="hibernate.current_session_context_class">thread</property>

       -->

      

       <mapping resource="com/ibm/pojo/Stu.hbm.xml" />

       <mapping resource="com/ibm/pojo/Logtb.hbm.xml" />

 

    </session-factory>

 

</hibernate-configuration>

 

Hibernate節點配置文件(一)

Stu.hbm.xml

<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!--

    Mapping file autogenerated by MyEclipse Persistence Tools

-->

<hibernate-mapping>

    <class name="com.ibm.pojo.Stu" table="stu" schema="dbo" catalog="ibm001">

        <id name="userid" type="java.lang.Integer">

            <column name="userid" />

            <generator class="native"></generator>

        </id>

        <property name="username" type="java.lang.String">

            <column name="username" length="32" />

        </property>

        <property name="pwd" type="java.lang.String">

            <column name="pwd" length="32" />

        </property>

    </class>

</hibernate-mapping>

 

 

JAVA代碼部分

Javabean

Stu.java

package com.ibm.pojo;

 

/**

 * Stu entity. @author MyEclipse Persistence Tools

 */

 

public class Stu implements java.io.Serializable {

 

    // Fields

 

    private Integer userid;

    private String username;

    private String pwd;

 

    // Constructors

 

    /** default constructor */

    public Stu() {

    }

 

    /** full constructor */

    public Stu(String username, String pwd) {

       this.username = username;

       this.pwd = pwd;

    }

 

    // Property accessors

 

    public Integer getUserid() {

       return this.userid;

    }

 

    public void setUserid(Integer userid) {

       this.userid = userid;

    }

 

    public String getUsername() {

       return this.username;

    }

 

    public void setUsername(String username) {

       this.username = username;

    }

 

    public String getPwd() {

       return this.pwd;

    }

 

    public void setPwd(String pwd) {

       this.pwd = pwd;

    }

 

}

 

從頁面來的數據傳到UserManagerAction,對象stu得到屬性值

UserManagerAction.java

package com.ibm.action;

 

import com.ibm.pojo.Stu;

import com.ibm.service.IUserOperService;

 

public class UserManagerAction {

    //定義一個stu對象

    private Stu stu;

    //定義一個service層的接口

    private IUserOperService service;

   

    public String  execute() {

        //調用service

       service.addUser(stu);

       System.out.println(stu.getUsername());

       return "success";

    }

   

    public Stu getStu() {

       return stu;

    }

   //set方法爲stu對象設置值

    public void setStu(Stu stu) {

       this.stu = stu;

    }

    public IUserOperService getService() {

       return service;

    }

    //action層通過Set方法注入接口IUserOperService

    public void setService(IUserOperService service) {

       this.service = service;

    }

}

 

//定義service接口

IuserOperService.java

package com.ibm.service;

 

import com.ibm.pojo.Stu;

 

public interface IUserOperService {

   

    public void addUser(Stu stu);

}

 

//接口service的實現類

UserOperService.java

package com.ibm.service.iservice;

 

import com.ibm.dao.IUserOperDAO;

import com.ibm.pojo.Stu;

import com.ibm.service.IUserOperService;

 

public class UserOperService implements IUserOperService{

    //定義用戶接口userOperDAO

    IUserOperDAO userOperDAO;

   

    public void addUser(Stu stu) {

       // TODO Auto-generated method stub

        //調用接口中實現類的add方法

       userOperDAO.add(stu);

    }

 

    //service層通過Set方法注入接口userOperDAO

    public void setUserOperDAO(IUserOperDAO userOperDAO) {

       this.userOperDAO = userOperDAO;

    }

}

 

定義功能接口IUserOperDAO

IUserOperDAO.java

package com.ibm.dao;

 

import com.ibm.pojo.Stu;

 

public interface IUserOperDAO {

    public void add(Stu stu);

}

 

功能接口IuserOperDAO實現類

UserOperDAO.java

package com.ibm.dao.idao;

 

import org.hibernate.Session;

import org.hibernate.Transaction;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

 

import com.ibm.dao.ILogOperDAO;

import com.ibm.dao.IUserOperDAO;

import com.ibm.factory.HibernateSessionFactory;

import com.ibm.pojo.Logtb;

import com.ibm.pojo.Stu;

 

/**

 * 編程式事務演示

 * @author Administrator

 *

 */

//public class UserOperDAO extends HibernateDaoSupport implements IUserOperDAO{

//

//  public void add(Stu stu) {

////       Session session=null;

////       Transaction tran=null;

////      

////       try {

////           session=HibernateSessionFactory.getSessionFactory().getCurrentSession();

////         

////          tran =session.beginTransaction();

////         

////          session.save(stu);

////         

////          ILogOperDAO logDAO=new LogOperDAO();

////          Logtb logTb=new Logtb();

////          logTb.setActionname("增加用戶");

////          logTb.setPersonid("U001");

////          logDAO.addLog(logTb);

////          tran.commit();

////         

////       } catch (Exception e) {

////          e.printStackTrace();

////          tran.rollback();

////       }

//  }

//

//}

  //繼承Spring中的HibernateDaoSupport類,並實現功能接口IUserOperDAO

  public class UserOperDAO extends HibernateDaoSupport implements IUserOperDAO{

 

       public void add(Stu stu){

//使用Spring自帶的事務管理器來管理sessionFactory(配置文件在Spring中的applicationContext-tran.xml),得到getHibernateTemplate()方法然後調用它的save方法保存數據

           this.getHibernateTemplate().save(stu);

       }

  }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章