1.建立web工程html
一路next 下去就行。完成後,IDEA會自動構建maven工程。java
2.建立以下項目結構node
須要將 java文件夾設置爲SourcesRoot目錄,不然沒法建立packagemysql
設置操做以下:選擇文件夾,右擊。web
3.在pom.xml文件中引入框架包spring
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.ssh</groupId> <artifactId>ssh</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>ssh Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.12.Final</version> </dependency> <!-- struts2 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.5.14.1</version> </dependency> <!-- struts2 spring 整合的核心包--> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.5.14.1</version> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>2.1_3</version> </dependency> <!--spring aop包 註釋方式使用事務管理 能夠不引用--> <dependency> <groupId>aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.5.0</version> </dependency> <dependency> <groupId>aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.5.0</version> </dependency> <!-- 添加對數據庫的支持 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.0.5</version> </dependency> <!-- https://mvnrepository.com/artifact/c3p0/c3p0 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> </dependencies> <build> <finalName>ssh</finalName> </build> </project>
4.配置web.xml文件sql
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>ssh</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </context-param> <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> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
5.配置spring的核心配置文件spring.xml,配置文件中掃描,注入各個javaBean,而且管理了hibernate的數據源和事務數據庫
--- jdbc配置文件 jdbc.propertiesexpress
mysql.driverClassName = com.mysql.jdbc.Driver mysql.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8 mysql.username = root mysql.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop "> <context:component-scan base-package="com.ssh.action"></context:component-scan> <context:component-scan base-package="com.ssh.service"></context:component-scan> <context:component-scan base-package="com.ssh.dao"></context:component-scan> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties"/> </bean> <!-- data connection setting --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${mysql.driverClassName}"></property> <property name="jdbcUrl" value="${mysql.url}"></property> <property name="user" value="${mysql.username}"></property> <property name="password" value="${mysql.password}"></property> <!-- 設置數據庫鏈接池的最大鏈接數 --> <property name="maxPoolSize"> <value>50</value> </property> <!-- 設置數據庫鏈接池的最小鏈接數 --> <property name="minPoolSize"> <value>5</value> </property> <!-- 設置數據庫鏈接池的初始化鏈接數 --> <property name="initialPoolSize"> <value>5</value> </property> <!-- 設置數據庫鏈接池的鏈接最大空閒時間 --> <property name="maxIdleTime"> <value>20</value> </property> <!-- c3p0緩存Statement的數量數 --> <property name="maxStatements"> <value>50</value> </property> <!-- 當鏈接池裏面的鏈接用完的時候,C3P0一下獲取新的鏈接數 --> <property name="acquireIncrement"> <value>20</value> </property> </bean> <!-- hibernate 管理--> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <!-- 引用上面設置的數據源 --> <property name="dataSource"> <ref bean="dataSource"/> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.autoReconnect">true</prop> <prop key="hibernate.connection.autocommit">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <!-- 解決session關閉問題 --> <prop key="hibernate.enable_lazy_load_no_trans">true</prop> <!-- spring 和 hibernate 整合的時候默認就是使用線程的,下面這一行不用寫,寫了反而要報錯,此外 sessionFaction,不能使用openSession 既不能保存數據到數據庫,還不能實現事務功能 --> <!--<prop key="current_session_context_class">thread</prop>--> <prop key="hibernate.max_fetch_depth">3</prop> <prop key="hibernate.connection.url" >jdbc:mysql://localhost:3306/test</prop> <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop> </props> </property> <!-- 包掃描的方式加載註解類 --> <property name="packagesToScan"> <list> <value>com.ssh.model</value> </list> </property> <property name="mappingLocations"> <list> <value>classpath:com/ssh/model/User.hbm.xml</value> </list> </property> </bean> <!-- 用註解來實現事物管理 --> <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <tx:annotation-driven transaction-manager="txManager"/> <!--<tx:advice id="txAdvice" transaction-manager="txManager">--> <!--<tx:attributes>--> <!--<tx:method name="*" read-only="false"/>--> <!--</tx:attributes>--> <!--</tx:advice>--> <!--<aop:config>--> <!--<aop:pointcut id="pt" expression="execution(* com.ssh.service.impl.*.*(..))"/>--> <!--<aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>--> <!--</aop:config>--> </beans>
6.配置struts2的核心配置文件struts.xmlapache
<?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"> <struts> <!-- 修改常量管理struts 中的action的工程,這個常量的使用,必須引入 spring和struts的整合包,否則spring沒法管理struts2 Action 中的實體類--> <constant name="struts.objectFactory" value="spring" />
<package name="user" extends="struts-default" namespace="/"> <action name="user_*" class="userAction" method="{1}"> <result name="success">/test.jsp</result> <allowed-methods>m1,saveUser</allowed-methods><!-- struts 2.5 以後,使用通配符必須加上這一行 ,不然沒法使用通配符訪問--> </action> </package> </struts>
7.使用IDEA生成數據庫對應實體類和hibernate的映射文件
第一步:鏈接數據庫
選擇後邊側邊欄的Database
第二步,生成映射文件
選中左邊側邊欄的Persistence菜單
等待生成映射文件,完成後,在對應的包 下面生成以下文件
USer 代碼
/** * FileName: User * Author: GET_CHEN * Date: 2017/12/13 13:45 * Description: */ package com.ssh.model; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class User { private int uid; private String uname; @Id @Column(name = "uid") public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } @Basic @Column(name = "uname") public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; if (uid != user.uid) return false; if (uname != null ? !uname.equals(user.uname) : user.uname != null) return false; return true; } @Override public int hashCode() { int result = uid; result = 31 * result + (uname != null ? uname.hashCode() : 0); return result; } }
USer.hbm.xml文件內容以下:
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.ssh.model.User" table="user" schema="test"> <id name="uid" column="uid"/> <property name="uname" column="uname"/> </class> </hibernate-mapping>
8.完成mvc的架構中,各個部分的代碼。
-- dao 層
接口UserDao代碼
/** * FileName: UserDao * Author: GET_CHEN * Date: 2017/12/13 11:34 * Description: */ package com.ssh.dao; import com.ssh.model.User; public interface UserDao { User getUser(Integer uid); void saveUser(User user); }
實現類UserDaoImpl的代碼
/** * FileName: UserDaoImpl * Author: GET_CHEN * Date: 2017/12/13 11:57 * Description: */ package com.ssh.dao; import com.ssh.model.User; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; @Repository("userDao") public class UserDaoImpl implements UserDao { @Resource(name="sessionFactory") private SessionFactory sessionFactory; public User getUser(Integer uid) { Session session = sessionFactory.getCurrentSession(); //當getCurrentSession所在的方法,或者調用該方法的方法綁定了事務以後,session就與當前線程綁定了,也就能經過currentSession來獲取,不然就不能。 User user = session.get(User.class, uid); // session.close(); return user; } public void saveUser(User user) { Session session = sessionFactory.getCurrentSession(); session.save(user); System.out.println("======="+user.getUname()); //使用getCurrentSession後,hibernate 本身維護session的關閉,寫了反而會報錯 } }
-- service層
接口UserService的代碼
/** * FileName: UserService * Author: GET_CHEN * Date: 2017/12/13 11:31 * Description: */ package com.ssh.service; import com.ssh.model.User; public interface UserService { User getUser(Integer uid); void saveUser(User user); }
實現類UserServiceImpl的代碼
/** * FileName: UserServiceImpl * Author: GET_CHEN * Date: 2017/12/13 11:32 * Description: */ package com.ssh.service.impl; import com.ssh.dao.UserDao; import com.ssh.model.User; import com.ssh.service.UserService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; @Service("userService") public class UserServiceImpl implements UserService { //依賴Dao @Resource private UserDao userDao; // 注入事務管理 @Transactional(rollbackFor={Exception.class, RuntimeException.class}) public User getUser(Integer uid) { return userDao.getUser(uid); } @Transactional(rollbackFor={Exception.class, RuntimeException.class}) public void saveUser(User user) { userDao.saveUser(user); // throw new RuntimeException(); // userDao.saveUser(user); } }
-- 控制層 Action
UserAction代碼以下
/** * FileName: TestAction * Author: GET_CHEN * Date: 2017/12/13 9:52 * Description: */ package com.ssh.action; import com.opensymphony.xwork2.ActionSupport; import com.ssh.model.User; import com.ssh.service.UserService; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import javax.annotation.Resource; @Controller("userAction") @Scope("prototype") public class UserAction extends ActionSupport{ //定義存放到值棧中的對象 private User user;
//依賴service @Resource private UserService userService; //實現要存放到值棧中對象的get方法 public User getUser() { return user; } public String m1(){ user = userService.getUser(1); System.out.println(user.getUname()); return SUCCESS; } public String saveUser(){ User user = new User(); user.setUname("事務提交"); userService.saveUser(user); return SUCCESS; } }
-- view層test.jsp頁面的代碼
<%-- Created by IntelliJ IDEA. User: GET_CHEN Date: 2017/12/13 Time: 13:57 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%-- 引入struts2 的標籤庫--%> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>ssh測試</title> </head> <body> <%-- 獲取值棧中的user對象的uname的值--%> 用戶名: <s:property value="user.uname"></s:property> </body> </html>
9.部署項目到Tomcat
-- 配置Tomcat
選擇上圖中的Configure進入,配置tomcat路徑
確認後,回到上級頁面,選擇Deployment菜單項,添加工程到Tomcat
10.啓動Tomcat,訪問Action中的方法
-- 切換到Tomcat,點擊綠色按鈕啓動Tomcat
-- 在地址欄輸入,以下地址。結果以下。
------------------ 今天分享處處
------------------By GET_CHEN