SSH第一篇【整合SSH步驟、OpenSessionInView】
阿新 • • 發佈:2019-01-09
前言
到目前為止,Struts2、Hibernate、Spring框架都過了一遍了。也寫過了Spring怎麼與Struts2整合,Spring與Hibernate整合…本博文主要講解SSH的整合
整合步驟:
- 1) 引入SSH Jar檔案
- Struts 核心jar
- Hibernate 核心jar
- Spring
- Core 核心功能
- Web 對web模組支援
- Aop aop支援
- Orm 對hibernate支援
- Jdbc/tx jdbc支援包、事務相關包
- 2)配置檔案
- Web.xml
- 初始化struts功能、spring容器
- Struts.xml 配置請求路徑與對映action的關係
- Spring.xml IOC容器配置
- bean-base.xml 【公用資訊】
- bean-service.xml
- bean-dao.xml
- bean-action.xml
- Web.xml
需求:員工與部門之間的關係。當操作員工的時候,可以得到員工所在的部門
引入jar檔案
配置檔案
web.xml配置檔案
初始化struts功能、spring容器
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!--初始化Struts功能-->
<filter>
<filter-name>struts2</filter-name>
<filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--初始化Spring容器-->
<!-- 2. spring 配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/bean*</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
Struts.xml
配置請求路徑與對映action的關係【記得繼承著struts-default】
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="aaa" extends="struts-default">
</package>
</struts>
SpringIOC容器配置
該Spring配置檔案配置著一些公用的資訊
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1) 連線池例項 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///zhongfucheng"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
<property name="initialPoolSize" value="3"></property>
<property name="maxPoolSize" value="6"></property>
</bean>
<!-- 2) SessionFactory例項建立 -->
<!-- 所有的配置都由spring維護(專案中不需要hibernate.cfg.xml啦) -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- a. 連線池 -->
<property name="dataSource" ref="dataSource"></property>
<!-- b. hibernate常用配置: 方言、顯示sql、自動建表等 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- c. 對映配置 -->
<property name="mappingLocations">
<list>
<value>classpath:zhongfucheng/entity/*.hbm.xml</value>
</list>
</property>
</bean>
<!-- 3) 事務配置 -->
<!-- # 事務管理器 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- # 事務增強 -->
<!-- <tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="*" read-only="false"/>
</tx:attributes>
</tx:advice>
<!– # AOP配置 –>
<aop:config>
<aop:pointcut expression="execution(* cn.itcast.service.*.*(..))" id="pt"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
</aop:config>-->
<!--4)開啟註解掃描器-->
<context:component-scan base-package="zhongfucheng"/>
<!--5)開啟註解處理事務-->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
編寫entity
需求:獲取使用者資訊的時,能夠得到使用者擁有的角色。
- Dept.java
package zhongfucheng.entity;
/**
* Created by ozc on 2017/5/15.
*/
public class Dept {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- User.java
package zhongfucheng.entity;
/**
* Created by ozc on 2017/5/15.
*/
public class User {
private String id;
private String username;
private Dept dept;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
}
entity的對映檔案
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 package="zhongfucheng.entity">
<class name="User" table="t_user">
<id name="id" column="user_id">
<generator class="native"></generator>
</id>
<property name="username" column="userName"></property>
<many-to-one name="dept" class="Dept" column="dept_id"/>
</class>
</hibernate-mapping>
Dept.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 package="zhongfucheng.entity">
<class name="Dept" table="t_dept">
<id name="id" column="deptId">
<generator class="native"></generator>
</id>
<property name="name" column="deptName"></property>
</class>
</hibernate-mapping>
編寫Dao
把Dao新增到容器上,並且得到sessionFactory物件
@Repository
public class UserDao {
@Autowired
private SessionFactory sessionFactory;
public User findbyId(int id) {
return (User) sessionFactory.getCurrentSession().get(User.class, id);
}
}
編寫Service
得到UserDao物件,把UserService新增到容器中
@Service
public class UserService {
@Autowired
private UserDao userDao;
public User findbyId(int id) {
return userDao.findbyId(id);
}
}
編寫Action
設定Action的例項為多例,得到userService物件,將查詢結果存放到request域物件中
@Controller
@Scope("prototype")
public class UserAction extends ActionSupport {
@Autowired
private UserService userService;
@Override
public String execute() throws Exception {
//假設查詢員工的主鍵為1
int user_id = 1;
User user = userService.findbyId(user_id);
//得到request物件,把資料存到request中
Map<String, Object> request = ActionContext.getContext().getContextMap();
request.put("user", user);
return SUCCESS;
}
}
Struts2配置檔案
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="aaa" extends="struts-default">
<action name="show" class="userAction" method="execute">
<result name="success">/show.jsp</result>
</action>
</package>
</struts>
JSP頁面程式碼
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
員工的姓名:${user.username}
</body>
</html>
測試效果
OpenSessionInView
我們在學習Hibernate的時候已經說過,Hibernate預設是開啟懶載入的。當用到物件的時候才去獲取資料…現在我在JSP頁面上獲取員工的部門是什麼,出現了錯誤
為什麼呢?Spring的事務控制是在Service層的,當Service層呼叫完之後,事務就會被提交。然而到了Action層的時候,事務已經關閉了。JSP就獲取不到事務關閉後的資料了!
Spring也知道我們Hibernate的懶載入技術,可能使我們老是自己寫攔截器去開啟Session,直到view層關閉。於是Spring提供了OpenSessionInView供我們使用:在web.xml檔案下配置就行了。
<!-- 配置spring的OpenSessionInView模式 【目的:JSp頁面訪問懶載入資料】 -->
<!-- 注意:訪問struts時候需要帶上*.action字尾 -->
<filter>
<filter-name>OpenSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInView</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>