快速整合ssh框架搭建簡單demo
eclipse建立專案
File -> new ->Dynamic Web Project
->next ->next
Generate web.xml deployment descriptor 打上勾,專案建立時會自動建立web.xml檔案。->finish
複製相關jar檔案到lib
struts2_lib
spring_lib
hibernate_lib
這三個lib目錄分別單獨屬於struts2、spring、hibernate三個框架,整合在一起的會有部分重複,刪除舊版本,保留新版本即可
三個框架整合是struts-spring.jar一定要加,除錯的時候忘記匯入這個包,spring和struts2整合瘋狂報錯,當時一臉懵
這裡推薦一個jar下載網站
需求:查詢資料庫中user表中的所有記錄,以表格形式顯示所有的記錄(user表字段【id,username,password】) 前期準備 在src檔案下新建下列包和.java,.xml檔案
public class Demo extends ActionSupport{ DemoService demoService; public void setDemoService(DemoService demoService) { this.demoService = demoService; } public String query() throws Exception{ List<User> list = demoService.queryAll(); //獲取值棧物件,將demoService返回的List<User>放入值棧中 ActionContext context = ActionContext.getContext(); ValueStack valueStack = context.getValueStack(); valueStack.set("users",list); return "query"; } }
User.java
package cn.sshdemo.entity;
public class User {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
DemoDao.java
public interface DemoDao {
//返回User集合
List<User> queryAll();
}
DemoDaoImpl.java 實現DemoDao介面
public class DemoDaoImpl extends HibernateDaoSupport implements DemoDao{
@Override
public List<User> queryAll() {
// TODO Auto-generated method stub
List<User> users = (List<User>)this.getHibernateTemplate().find("from User");
return users;
}
}
DemoService.java 類名上新增事務註解
@Transactional
public class DemoService {
DemoDao demoDao;
public void setDemoDao(DemoDao demoDao) {
this.demoDao = demoDao;
}
public List<User> queryAll(){
return demoDao.queryAll();
}
}
WebContent 下新建index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!--載入struts2標籤庫-->
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<table>
<tr>
<th>id</th>
<th>username</th>
<th>password</th>
</tr>
<!--使用ognl表示式迴圈生成表格記錄-->
<s:iterator value="users">
<tr>
<td><s:property value="id"/></td>
<td><s:property value="username"/></td>
<td><s:property value="password"/></td>
</tr>
</s:iterator>
</table>
</body>
</html>
搭建struts2環境 (1)建立struts.xml,在xml中配置action
<!--伺服器解析客戶端的請求,對映到Demo中的某個方法,將呼叫方法的返回值和result中name值比較,確定跳轉至哪個頁面
method="{1}" 對應著demo_*的*,比如demo_action,則會呼叫Demo中的action()方法
-->
<?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="demo" extends="struts-default" >
<action name="demo_*" class="cn.sshdemo.action.Demo" method="{1}">
<result name="query">index.jsp</result>
</action>
</package>
</struts>
(2)在web.xml中配置struts2的過濾器
<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>
搭建hibernate環境 建立hibernate.cfg.xml 配置資料庫連線資訊、對映檔案
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">【資料庫url地址】</property>
<property name="hibernate.connection.username">【使用者名稱】</property>
<property name="hibernate.connection.password">【密碼】</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- update 沒有表,建立表,已有表,更新表 -->
<property name="hibernate.hbm2ddl.auto" >update</property>
<!-- 配置資料庫方言
在mysql裡面實現分頁關鍵字limit,只能使用在mysql裡面
在oracle資料庫,實現分頁rownum
讓hibernate框架識別不同資料庫中特有的語句
-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="cn/sshdemo/entity/user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
建立對映配置檔案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="cn.sshdemo.entity.User" table="m_user">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="username" column="username"></property>
<property name="password" column="password"></property>
</class>
</hibernate-mapping>
搭建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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
</beans>
web.xml中相關配置
<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>
struts2和spring整合 配置applicationContext.xml spring核心功能之一IOC:控制反轉,將例項化物件交由spring處理。這裡生成demoService、demoDaoImpl分別通過set方法注入到DemoAction、DemoService中去
<bean id="demoAction" class="cn.sshdemo.action.Demo" scope="prototype">
<property name="demoService" ref="demoService"></property>
</bean>
<bean id="demoService" class="cn.sshdemo.service.DemoService">
<property name="demoDao" ref="demoDaoImpl"></property>
</bean>
<bean id="demoDaoImpl" class="cn.sshdemo.daoImpl.DemoDaoImpl">
<property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean>
修改struts.xml檔案,action的class修改為demoAction,因為該物件已由spring建立
<?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="demo" extends="struts-default" >
<action name="demo_*" class="demoAction" method="{1}">
<result name="query">index.jsp</result>
</action>
</package>
</struts>
hibernate和spring整合 在applicationContext.xml中配置dataSource、sessionFactory等相關資訊
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/spring" />
<property name="username" value="root" />
<property name="password" value="895772" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocations" value="classPath:hibernate.cfg.xml"></property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
註釋掉hibernate.cfg.xml中配置的資料庫連線資訊,因為已由spring配置完畢
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">...............</property>
<property name="hibernate.connection.username">.........</property>
<property name="hibernate.connection.password">..........</property> -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- update 沒有表,建立表,已有表,更新表 -->
<property name="hibernate.hbm2ddl.auto" >update</property>
<!-- 配置資料庫方言
在mysql裡面實現分頁關鍵字limit,只能使用在mysql裡面
在oracle資料庫,實現分頁rownum
讓hibernate框架識別不同資料庫中特有的語句
-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="cn/sshdemo/entity/user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
配置事務 在applicationContext.xml中新增一下程式碼
<!-- 配置事務 -->
<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<!-- 注入sessionFactory -->
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 開啟事務註解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
執行 右鍵add and remove,將要執行的專案新增進 Configured 右鍵start,伺服器啟動。檢視console,如果程式沒有問題,控制檯不會有異常丟擲且資料庫會自動生成m_user表,如果出現異常,則根據異常一步步排查錯誤 開啟chrome瀏覽器,位址列中輸入localhost:8080/sshdemo/demo_query.action 呼叫Demo中的query方法 因為資料庫中只插了一行記錄,當然只有一行顯示啦== 如果出現404錯誤,檢查路徑;出現500錯誤,檢查程式碼就行了:)