【本文版權歸微信公衆號"代碼藝術"(ID:onblog)全部,如果轉載請務必保留本段原創聲明,違者必究。】html
1.新建Maven項目,導入相關依賴(推薦)
若不使用maven:請前往Maven官網依次下載jar包導入)java
<properties> <!-- 統一源碼的編碼方式 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- 統一各個框架版本 --> <spring.version>4.3.7.RELEASE</spring.version> <hibernate.version>4.3.10.Final</hibernate.version> <struts2.version>2.5.5</struts2.version> </properties> <dependencies> <!-- junit依賴 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!--補全項目依賴 --> <!--1.日誌 java日誌有:slf4j,log4j,logback,common-logging slf4j:是規範/接口 日誌實現:log4j,logback,common-logging 使用:slf4j+ --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> </dependency> <!--2.數據庫相關依賴 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.1</version> </dependency> <!--2.dao框架:hibernate-lib-required依賴 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <!--1) hibernate-lib-jpa/包 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <!--3.Servlet web相關依賴 --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <!--4.spring依賴 --> <!--1)IOC依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${spring.version}</version> </dependency> <!--2)spring AOP依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.aopalliance</groupId> <artifactId>com.springsource.org.aopalliance</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.8</version> </dependency> <!--3)spring dao層依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <!--4)spring 事務管理 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <!--5)spring web相關依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <!--6)spring test相關依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!--7)spring log4j 日誌記錄 --> <dependency> <groupId>org.apache.log4j</groupId> <artifactId>com.springsource.org.apache.log4j</artifactId> <version>1.2.15</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>com.springsource.org.apache.commons.logging</artifactId> <version>1.1.1</version> </dependency> <!--5.struts2 依賴 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>${struts2.version}</version> </dependency> <!--1)Struts2整合Spring --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>${struts2.version}</version> </dependency> <!--2)Struts2註解開發 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-convention-plugin</artifactId> <version>${struts2.version}</version> </dependency> </dependencies>
2.在WEB-INF的web.xml中進行配置mysql
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>ssh</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 配置Struts2過濾器 --> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置Spring的監聽器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 指定Spring配置文件所在路徑 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-*.xml</param-value> </context-param> </web-app>
3.建立entity包,建立數據庫相關實體類web
package cn.zyzpp.domain; public class Product { private Integer pid; private String pname; private Double price; public Product() { super(); } public Product(Integer pid, String pname, Double price) { super(); this.pid = pid; this.pname = pname; this.price = price; } public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } @Override public String toString() { return "pname:" + getPname() + ";price:" + getPrice(); } }
4.根據實體類建立**.hbm.xml映射文件(移動到resources/mapper下)spring
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated 2018-2-21 14:13:05 by Hibernate Tools 3.5.0.Final --> <hibernate-mapping> <class name="cn.zyzpp.domain.Product" table="product"> <id name="pid" type="java.lang.Integer"> <!-- 主鍵 --> <column name="pid" /> <!-- 數據庫字段 --> <generator class="increment" /> <!-- 主鍵策略:自動; assigned:手動--> </id> <property name="pname" type="java.lang.String"> <column name="pname" /> </property> <property name="price" type="java.lang.Double"> <column name="price" /> </property> </class> </hibernate-mapping>
或者直接在實體類中使用註釋sql
package cn.zyzpp.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; /** * hibernate註釋演示 */ @Entity @Table(name = "EMPLOYEE") public class Employee { @Id //定義主鍵 @GeneratedValue(strategy=GenerationType.IDENTITY) //主鍵生成策略:自動選擇; mysql會自增 @Column(name = "id") //對應數據庫字段 private int id; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; @Column(name = "salary") private int salary; public Employee() { //@Entity規定必須有的構造方法 } public Employee(String firstName, String lastName, int salary) { super(); this.firstName = firstName; this.lastName = lastName; this.salary = salary; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String first_name) { this.firstName = first_name; } public String getLastName() { return lastName; } public void setLastName(String last_name) { this.lastName = last_name; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } }
補充一步:新建ProductDao.java數據庫
public class ProductDao extends HibernateDaoSupport { public void saveProduct(Product product){ System.out.println("注入sessionFactory後,能夠直接調用HibernateTemplate"); this.getHibernateTemplate().save(product); } }
5.在resources下建立spring文件夾,新建spring-dao.xml,添加兩者整合配置。express
/*推薦在resources下新建jdbc.properties而不是直接使用*/ jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/domain?useUnicode=true&characterEncoding=utf-8 jdbc.username=root jdbc.password=
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd"> <!-- Spring配置整合hibernate過程 --> <!-- 1:配置數據庫相關參數properties的屬性:${url} --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 2:數據庫鏈接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 配置鏈接池屬性 --> <property name="driverClass" value="${jdbc.driver}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- c3p0鏈接池的私有屬性 --> <property name="maxPoolSize" value="30" /> <property name="minPoolSize" value="10" /> <!-- 關閉鏈接後不自動commit --> <property name="autoCommitOnClose" value="false" /> <!-- 獲取鏈接超時時間 --> <property name="checkoutTimeout" value="3000" /> <!-- 當獲取鏈接失敗重試次數 --> <property name="acquireRetryAttempts" value="2" /> </bean> <!-- 3:配置hibernate4的相關屬性 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <!-- 注入鏈接池 --> <property name="dataSource" ref="dataSource"></property> <!-- 配置Hibernate的屬性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop><!-- 方言 --> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop><!-- 更新表結構:有表使用無表建立 --> </props> </property> <!-- 加載Hibernate4中的映射文件 --> <property name="mappingLocations"> <list> <value>classpath:mapper/*.hbm.xml</value> </list> </property> <!-- 或者:配置實體註解掃描 --> <!-- <property name="packagesToScan">--> <!-- <list>--> <!-- <value>cn.zyzpp.domain</value>--> <!-- </list>--> <!-- </property>--> </bean> <!-- 配置DAO的類 --> <bean id="productDao" class="cn.zyzpp.dao.ProductDao"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans>
6.在spring文件夾下新建spring-service.xml,配置service層的相關bean。apache
package cn.zyzpp.service; import org.springframework.transaction.annotation.Transactional; import cn.zyzpp.dao.ProductDao; import cn.zyzpp.domain.Product; @Transactional public class ProductService { //業務層注入Dao的類 private ProductDao productDao; public void setProductDao(ProductDao productDao) { this.productDao = productDao; } /** * 業務層保存方法 * @param product */ public void save(Product product){ System.out.println("service中的save方法執行了"); productDao.saveProduct(product); } }
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd"> <!-- 配置業務類 --> <bean id="productService" class="cn.zyzpp.service.ProductService"> <property name="productDao" ref="productDao"></property> </bean> <!--配置事務管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <!--注入數據庫鏈接池 --> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!--開啓註解事務 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
7.建立.action包, 新建Action類api
package cn.zyzpp.action; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import cn.zyzpp.domain.Product; import cn.zyzpp.service.ProductService; public class ProductAction extends ActionSupport implements ModelDriven<Product> { // 模型驅動使用的類 private Product product = new Product(); @Override public Product getModel() { return product; } // struts2和spring整合過程按名稱自動注入的業務類 private ProductService productService; public void setProductService(ProductService productService) { this.productService = productService; } /** * Action響應 * * @param product * @return * @throws IOException */ public String save() throws IOException { System.out.println("action中的save方法執行了:" + product.toString()); productService.save(product); return NONE; } }
8.在spring文件夾下建立spring-web.xml配置struts2的Action類
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd"> <!-- Spring配置Struts2的Action類 --> <bean id="productAction" class="cn.zyzpp.action.ProductAction" scope="prototype"> <property name="productService" ref="productService"></property> </bean> </beans>
9.在resources下新建struts.xml並配置action等
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <!-- struts2整合spring第一種方式 :仍是由struts2.xml配置action <struts> <package name="ssh" extends="struts-default" namespace="/"> <action name="product_*" class="cn.zyzpp.action.ProductAction" method="{1}"> </action> </package> </struts>--> <!-- struts2整合spring第二種方式 :由spring容器管理action類 :類路徑改成id值便可--> <struts> <package name="ssh" extends="struts-default" namespace="/"> <action name="product_*" class="productAction" method="{1}"> </action> </package> <!-- 改變action 後戳 --> <constant name="struts.action.extension" value=",html"></constant> </struts>
10.在resources下建立log4j.properties文件便可。
log4j.rootLogger=debug, stdout #log4j.logger.org.mybatis.example.BlogMapper=TRACE log4j.appender.stdout=org.apache.log4j.ConsoleAppender >【本文版權歸微信公衆號"代碼藝術"(ID:onblog)全部,如果轉載請務必保留本段原創聲明,違者必究。!】 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[%t] %-5p [%c] - %m%n #DEBUG < INFO < WARN < ERROR <FATAL<br /><br />
最後,使用Tomcat的Maven插件,執行mvn tomcat:run啓動項目!
<plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <hostName>localhost</hostName> <uriEncoding>UTF-8</uriEncoding> <path>/</path> <port>8080</port> </configuration> </plugin></plugins>
【本文版權歸微信公衆號"代碼藝術"(ID:onblog)全部,如果轉載請務必保留本段原創聲明,違者必究。】