Java进阶知识27 SSH整合(Struts2、Spring、Hibernate)

1、我用到的jar包  

    

2、整合实例  

2.1、MySQL数据库建表语句

1 create database school; -- 创建数据库
2 use school; -- 使用school数据库
3 4 create table user( -- 创建user表
4   id int(4) primary key auto_increment,
5   name varchar(20) not null,
6   age int(4) not null
7 );
8 inert into user(name,age) values("张三",18);

2.2、配置web.xml文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
 3   <display-name></display-name>
 4   <welcome-file-list>
 5     <welcome-file>index.jsp</welcome-file>
 6   </welcome-file-list>
 7   
 8   <!-- Spring监听器 -->
 9   <context-param>
10         <param-name>contextConfigLocation</param-name>
11         <param-value>/WEB-INF/classes/beans_*.xml</param-value>
12     </context-param>
13     <listener>
14         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
15     </listener>
16 
17     <!-- Struts2过滤器 -->
18     <filter>
19         <filter-name>struts2</filter-name>
20         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
21     </filter>
22     <filter-mapping>
23         <filter-name>struts2</filter-name>
24         <url-pattern>/*</url-pattern>
25     </filter-mapping>
26 </web-app>

2.3、创建实体类(User)

 1 package com.shore.entity;
 2 
 3 /**
 4  * @author DSHORE/2019-11-12
 5  * 
 6  */
 7 public class User {
 8     private Integer id;
 9     private String name;
10     private Integer age;
11 
12     public Integer getId() {
13         return id;
14     }
15     public void setId(Integer id) {
16         this.id = id;
17     }
18 
19     public String getName() {
20         return name;
21     }
22     public void setName(String name) {
23         this.name = name;
24     }
25 
26     public Integer getAge() {
27         return age;
28     }
29     public void setAge(Integer age) {
30         this.age = age;
31     }
32 }

2.4、配置实体类User的hibernate文件(User.hbm.xml)

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC
 3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 5         
 6 <hibernate-mapping package="com.shore.entity">
 7     <class name="User">  
 8         <id name="id"> 
 9             <generator class="native"/>
10         </id>
11         <property name="name" type="java.lang.String"/> 
12         <property name="age" type="java.lang.Integer"/> 
13     </class>
14 </hibernate-mapping>

2.5、创建dao层IUserDao接口类以及UserDao接口实现类

 1 //接口类
 2 public interface IUserDao {
 3     public User getByName(String name);//根据用户名查询
 4 }
 5 
 6 //对应的接口实现类
 7 public class UserDao implements IUserDao {
 8     //从IoC容器注入SessionFactory
 9     private SessionFactory sessionFactory;
10     public void setSessionFactory(SessionFactory sessionFactory) {
11         this.sessionFactory = sessionFactory;
12     }
13     
14     @Override  //根据用户名查询
15     public User getByName(String name) {
16         Query query = sessionFactory.getCurrentSession().createQuery("from User where name=:name");  //:name是命名参数
17         query.setParameter("name", name);
18         @SuppressWarnings("unchecked")
19         List<User> users = query.list();
20         if (users != null && users.size() > 0) {
21             return users.get(0);
22         }
23         return null;
24     }
25 }

2.6、创建service层IUserService接口类以及UserService接口实现类

 1 //接口类
 2 public interface IUserService {
 3     public User getByName(String name);
 4 }
 5 
 6 //对应的接口实现类
 7 public class UserService implements IUserService {
 8 
 9     private IUserDao userDao;
10     public void setUserDao(IUserDao userDao) {
11         this.userDao = userDao;
12     }
13     
14     @Override
15     public User getByName(String name) {
16         return userDao.getByName(name);
17     }
18 }

2.7、创建UserAction

 1 package com.shore.action;
 2 
 3 import com.opensymphony.xwork2.ActionSupport;
 4 import com.shore.service.IUserService;
 5 
 6 /**
 7  * @author DSHORE/2019-11-16
 8  *
 9  */
10 public class UserAction extends ActionSupport{
11     private static final long serialVersionUID = -3099218232367860074L;
12     
13     private IUserService userService;
14     
15     public String login() {
16         System.out.println(userService.getByName("张三"));
17         return SUCCESS;
18     }
19     
20     public void setUserService(IUserService userService) {
21         this.userService = userService;
22     }
23 }

2.8、配置Spring文件(beans_common.xml)

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xmlns:tx="http://www.springframework.org/schema/tx"
 6     xsi:schemaLocation="
 7        http://www.springframework.org/schema/beans
 8        http://www.springframework.org/schema/beans/spring-beans.xsd
 9        http://www.springframework.org/schema/tx
10        http://www.springframework.org/schema/tx/spring-tx.xsd
11        http://www.springframework.org/schema/aop
12        http://www.springframework.org/schema/aop/spring-aop.xsd">
13 
14     <!-- c3p0数据库连接池配置 -->
15     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
16         <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
17         <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/school"></property>
18         <property name="user" value="root"></property>
19         <property name="password" value="root"></property>
20         <property name="initialPoolSize" value="3"></property>
21         <property name="maxPoolSize" value="100"></property>
22         <property name="maxStatements" value="200"></property>
23         <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
24         <property name="acquireIncrement" value="2"></property>
25     </bean>
26 
27     <!-- Hibernate核心配置文件(hibernate.cfg.xml)全交给Spring去管理 -->
28     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
29         <!-- c3p0的数据库连接池 -->
30         <property name="dataSource" ref="dataSource"></property>
31         <!-- Hibernate基础参数配置 -->
32         <property name="hibernateProperties">
33             <props>  <!-- 注意:这个是Spring配置文件,故下面的key要写全名,即:前面加上hibernate.xxxxxx -->
34                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
35                 <prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
36                 <prop key="hibernate.show_sql">true</prop>
37                 <prop key="hibernate.format_sql">true</prop>
38                 <prop key="hibernate.hbm2ddl.auto">update</prop>
39             </props>
40         </property>
41         <!-- Hibernate 映射文件的配置 -->
42         <property name="mappingLocations">
43             <list>
44                 <value>classpath:com/shore/entity/*.hbm.xml</value>
45             </list>
46         </property>
47     </bean>
48 
49     <!-- dao层 -->
50     <bean id="userDao" class="com.shore.dao.impl.UserDao">
51         <property name="sessionFactory" ref="sessionFactory"></property>  
52     </bean>
53     
54     <!-- service层 -->
55     <bean id="userService" class="com.shore.service.impl.UserService">
56         <property name="userDao" ref="userDao"></property>
57     </bean>
58     
59     <!-- action层 -->
60     <bean id="userAction" class="com.shore.action.UserAction" scope="prototype">
61         <property name="userService" ref="userService"></property>
62     </bean>
63     
64     <!-- ############Spring声明式事务管理配置########### -->
65     <!-- 配置事务管理器 -->
66     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
67         <property name="sessionFactory" ref="sessionFactory"></property>
68     </bean>
69     
70     <!-- 配置事务增强(针对DAO层) -->
71     <tx:advice transaction-manager="transactionManager" id="transactionAdvice">
72         <tx:attributes>  <!-- *代表DAO层的所有方法 -->
73             <tx:method name="*" read-only="false"/>
74         </tx:attributes>
75     </tx:advice>
76     
77     <!-- AOP配置:配置切入点表达式 -->
78     <aop:config>    <!-- 第一个*表示返回值类型;第二个*表示service层下的所有接口实现类;第三个*表示每个接口实现类下的所有方法 -->
79         <aop:pointcut expression="execution(* com.shore.service.impl.*.*(..))" id="pt"/>
80         <aop:advisor advice-ref="transactionAdvice" pointcut-ref="pt"/>
81     </aop:config>
82 </beans>

2.9、配置Struts2 文件(struts.xml)

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 4     "http://struts.apache.org/dtds/struts-2.3.dtd">
 5 
 6 <struts>
 7     <!-- true支持动态方法调用 -->
 8     <constant name="struts.enable.DynamicMethodInvocation" value="true" />
 9     <constant name="struts.devMode" value="true" /> <!-- true -->
10 
11 
12     <package name="user" namespace="/user" extends="struts-default">
13         <action name="userAction" class="com.shore.action.UserAction">
14             <result name="success">/success.jsp</result>
15         </action>
16     </package>
17 </struts>

测试结果图:

  

 

总结:

  1、与传统方式相比,SSH框架 代码层(dao层、service层 等)耦合度较低,方便后期维护。

  2、entity、dao、service、action层、以及db层(连接数据库)都交给spring IOC容器来管理,大大降低各层之间的耦合度,极大方便该项目后期的维护。

  3、Hibernate或Spring IOC容器管理project与DB之间的连接Spring IOC容器管理dao层(及BaseDao)、service层、action层Struts2管理action层与前端页面的数据交互

 

 

 

 

 

原创作者:DSHORE

作者主页:http://www.cnblogs.com/dshore123/

原文出自:https://www.cnblogs.com/dshore123/p/11874947.html

版权声明:欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!

posted @ 2019-11-17 01:13  DSHORE  阅读(266)  评论(0编辑  收藏  举报