SSH說的上是javaweb經典框架,不能說100%要會SSH框架,但是大部分公司都在用,說到框架,都會提到ssh吧,這次就以很簡單的註冊例子來整合SSH框架。整合框架要注意的是先每個框架單獨測通後再整合,不然整合後出現問題比較難排查。
環境:windows + MyEclipse + JDK1.7 + Tomcat7 + MySQL
程式碼已經測通,如果有報錯可能是我某些地方沒描述清楚,請留言。
一、整合原理
二、導包(41個)
1.hibernate
# (1)hibernate/lib/required
(2)hibernate/lib/jpa | java persist api java的持久化規格(介面)
(3)資料庫驅動程式
2.struts2
# (1)struts-blank.war/WEB-INF /lib/*
注意:javassist-3.18.1-GA.jar套件與hibernate中的重複(只保留高版本即可)
# (2)struts整合spring插件包
注意:這個包一旦導入,那麼struts2在啟動時就會尋找spring容器.找不到將會拋出異常
3.spring
(1)基本:4+2
core | beans | context | expression | logging | log4j
(2)整合web (2)整合web (2)整合web (2)整合web (2)整合web (2)整合web (2)。 :web套件
spring-web
(3)整合aop:4個
spring-aop | spring-aspect | aop聯盟| aopweaving
(4)整合Hibernate和事務:4個
spring-jdbc | spring-tx | c3p0 | spring-orm
(5)整合junit4測試:test包
(5)整合junit4測試:test包1.建立applicationContextContext .xml,並導入約束(4個) beans | context | aop | tx
<?xml version="1.0" encoding="UTF-8"?><beans><bean></bean></beans>2.設定spring隨專案啟動(web.xml )
<!-- 让spring随web启动而创建的监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置spring配置文件位置参数 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>四、單獨設定struts2 1.設定struts2主設定檔(struts.xml)
<?xml version="1.0" encoding="UTF-8"?> nbsp;struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"><struts><package><action><result>/success.jsp</result></action></package></struts>
<!-- 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>
五、struts2與spring整合
struts2-spring-plugin-2.3.24.jar
2.配置常量 查看默認配置文件從31行開始找到要配置的變數。
### if specified, the default object factory can be overridden here ### Note: short-hand notation is supported in some cases, such as "spring" ### Alternatively, you can provide a com.opensymphony.xwork2.ObjectFactory subclass name here # struts.objectFactory = spring ### specifies the autoWiring logic when using the SpringObjectFactory. ### valid values are: name, type, auto, and constructor (name is the default) struts.objectFactory.spring.autoWire = name新增常數到struts.xml
<!-- # struts.objectFactory = spring 将action的创建交给spring容器
struts.objectFactory.spring.autoWire = name spring负责装配Action依赖属性--><constant></constant>
# 3.整合方案1:struts2自行建立action,spring負責組裝依賴屬性(了解)
<!-- 整合方案1:class属性上仍然配置action的完整类名 struts2仍然创建action,由spring负责组装Action中的依赖属性 --><action><result>/index.htm</result><result>/login.jsp</result></action>
4.整合方案2:spring負責創建action以及組裝.(推薦)
applicationContext.xml:<!-- action --><!-- 注意:Action对象作用范围一定是多例的.这样才符合struts2架构 --><bean><property></property></bean>

<!-- 整合方案2:class属性上填写spring中action对象的BeanName 完全由spring管理action生命周期,包括Action的创建 注意:需要手动组装依赖属性 --><action><result>/index.htm</result><result>/login.jsp</result></action>
package cn.xyp.web.domain;import java.util.HashSet;import java.util.Set;public class User {private Long user_id;private String user_code;private String user_name;private String user_password;private Character user_state;public Long getUser_id() {return user_id; }public void setUser_id(Long user_id) {this.user_id = user_id; }public String getUser_code() {return user_code; }public void setUser_code(String user_code) {this.user_code = user_code; }public String getUser_name() {return user_name; }public void setUser_name(String user_name) {this.user_name = user_name; }public String getUser_password() {return user_password; }public void setUser_password(String user_password) {this.user_password = user_password; }public Character getUser_state() {return user_state; }public void setUser_state(Character user_state) {this.user_state = user_state; } @Overridepublic String toString() {return "User [user_id=" + user_id + ", user_code=" + user_code + ", user_name=" + user_name + ", user_password=" + user_password + "]"; } }
<?xml version="1.0" encoding="UTF-8"?>nbsp;hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping><class><id><generator></generator></id><property></property><property></property><property></property><property></property></class></hibernate-mapping>####### User.hbm.xml:######
<?xml version="1.0" encoding="UTF-8"?>nbsp;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>com.mysql.jdbc.Driver</property> <!-- 数据库url --><property>jdbc:mysql:///crm_32</property> <!-- 数据库连接用户名 --><property>root</property> <!-- 数据库连接密码 --><property>1234</property><!-- 数据库方言 注意: MYSQL在选择方言时,请选择最短的方言. --><property>org.hibernate.dialect.MySQLDialect</property> <!-- 将hibernate生成的sql语句打印到控制台 --><property>true</property><!-- 将hibernate生成的sql语句格式化(语法缩进) --><property>true</property><!-- 自动导出表结构. 自动建表 --><property>update</property> <!-- 引入实体配置文件 --><mapping></mapping><mapping></mapping><mapping></mapping></session-factory></hibernate-configuration>###### 2.設定主設定檔(hibernate.xml)######
<!-- 加载配置方案1:仍然使用外部的hibernate.cfg.xml配置信息 --><bean><property></property></bean>####
七、spring整合hibernate
1.整合原理
将sessionFactory对象交给spring容器管理
2.在spring中配置sessionFactory
(1)配置方案一:(了解)
<!-- 加载配置方案1:仍然使用外部的hibernate.cfg.xml配置信息 --><bean><property></property></bean>
(2)配置方案二:(推荐)
<!-- 加载配置方案2:在spring配置中放置hibernate配置信息 --><bean><!-- 将连接池注入到sessionFactory, hibernate会通过连接池获得连接 --><property></property><!-- 配置hibernate基本信息 --><property><props><!-- 必选配置 --><prop>com.mysql.jdbc.Driver</prop><prop>jdbc:mysql:///crm_32</prop><prop>root</prop><prop>1234</prop> <prop>org.hibernate.dialect.MySQLDialect</prop><!-- 可选配置 --><prop>true</prop><prop>true</prop><prop>update</prop></props></property><!-- 引入orm元数据,指定orm元数据所在的包路径,spring会自动读取包中的所有配置 --><property></property></bean>
八、spring整合c3p0连接池
1.配置db.properties
jdbc.jdbcUrl=jdbc:mysql:///xyp_crm jdbc.driverClass=com.mysql.jdbc.Driver jdbc.user=root jdbc.password=123456
2.引入连接池到spring中
<!-- 读取db.properties文件 --><property-placeholder></property-placeholder><!-- 配置c3p0连接池 --><bean><property></property><property></property><property></property><property></property></bean>
3.将连接池注入给SessionFactory
<bean><!-- 将连接池注入到sessionFactory, hibernate会通过连接池获得连接 --><property></property></bean>
九、spring整合hibernate环境操作数据库
1.Dao类创建:继承HibernateDaoSupport
注意:项目中要确保使用统一版本。
//HibernateDaoSupport 为dao注入sessionFactorypublic class UserDaoImpl extends HibernateDaoSupport implements UserDao {
2.hibernate模板的操作
(1)execute
@Overridepublic User getByUserCode(final String usercode) {//HQLreturn getHibernateTemplate().execute(new HibernateCallback<user>() { @Overridepublic User doInHibernate(Session session) throws HibernateException { String hql = "from User where user_code = ? "; Query query = session.createQuery(hql); query.setParameter(0, usercode); User user = (User) query.uniqueResult();return user; } });</user>
(2)findByCriteria
//CriteriaDetachedCriteria dc = DetachedCriteria.forClass(User.class); dc.add(Restrictions.eq("user_code", usercode)); List<user> list = (List<user>) getHibernateTemplate().findByCriteria(dc); if(list != null && list.size()>0){return list.get(0); }else{return null; }</user></user>
3.spring中配置dao
<!-- Dao --><bean><!-- 注入sessionFactory --><property></property></bean>
十、spring的aop事务
1.准备工作
<!-- 核心事务管理器 --><bean><property></property></bean>
2.xml配置aop事务
(1)配置通知
<!-- 配置通知 --><advice> <attributes><method></method> <method></method> <method></method> <method></method> <method></method> <method></method> <method></method> <method></method> </attributes> </advice>
(2)配置织入
<!-- 配置将通知织入目标对象 配置切点 配置切面 --><config> <pointcut></pointcut> <advisor></advisor> </config>
3.注解配置aop事务
(1)开启注解事务
<!-- 开启注解事务 --><annotation-driven></annotation-driven>
(2)Service类中使用注解
@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=true)public class UserServiceImpl implements UserService{
@Override @Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)public void saveUser(User u) { ud.save(u); }
十一、扩大session作用范围
1.配置filter
为了避免使用懒加载时出现no-session问题.需要扩大session的作用范围。
<!-- 扩大session作用范围 注意: 任何filter一定要在struts的filter之前调用 因为struts是不会放行的 --> <filter> <filter-name>openSessionInView</filter-name> <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>openSessionInView</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
十二、练习:用户登录
1.struts.xml核心配置
<struts><!-- # struts.objectFactory = spring 将action的创建交给spring容器 struts.objectFactory.spring.autoWire = name spring负责装配Action依赖属性--><constant></constant><package><global-exception-mappings><exception-mapping></exception-mapping></global-exception-mappings> <!-- 整合方案:class属性上填写spring中action对象的BeanName 完全由spring管理action生命周期,包括Action的创建 注意:需要手动组装依赖属性 --><action><result>/index.htm</result><result>/login.jsp</result></action></package></struts>
2.Action代码
public class UserAction extends ActionSupport implements ModelDriven<user> {private User user = new User(); private UserService userService ; public void setUserService(UserService userService) {this.userService = userService; } public String login() throws Exception { // 1 调用Service执行登陆逻辑User u = userService.getUserByCodePassword(user); // 2 将返回的User对象放入session域ActionContext.getContext().getSession().put("user", u);// 3 重定向到项目首页return "toHome"; } @Overridepublic User getModel() {return user; } }</user>
2.Service核心代码
public User getUserByCodePassword(User u) { // 1 根据登陆名称查询登陆用户User existU = ud.getByUserCode(u.getUser_code());// 2 判断用户是否存在.不存在=>抛出异常,提示用户名不存在if (existU == null) {throw new RuntimeException("用户名不存在!"); } // 3 判断用户密码是否正确=>不正确=>抛出异常,提示密码错误if (!existU.getUser_password().equals(u.getUser_password())) {throw new RuntimeException("密码错误!"); } // 4 返回查询到的用户对象return existU; }
3.Dao核心代码
public User getByUserCode(final String usercode) { //CriteriaDetachedCriteria dc = DetachedCriteria.forClass(User.class); dc.add(Restrictions.eq("user_code", usercode)); List<user> list = (List<user>) getHibernateTemplate().findByCriteria(dc); if(list != null && list.size()>0){return list.get(0); }else{return null; } }</user></user>
以上是SSH中三大框架整合詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本文討論了使用Maven和Gradle進行Java項目管理,構建自動化和依賴性解決方案,以比較其方法和優化策略。

本文使用Maven和Gradle之類的工具討論了具有適當的版本控制和依賴關係管理的自定義Java庫(JAR文件)的創建和使用。

本文討論了使用咖啡因和Guava緩存在Java中實施多層緩存以提高應用程序性能。它涵蓋設置,集成和績效優勢,以及配置和驅逐政策管理最佳PRA

本文討論了使用JPA進行對象相關映射,並具有高級功能,例如緩存和懶惰加載。它涵蓋了設置,實體映射和優化性能的最佳實踐,同時突出潛在的陷阱。[159個字符]

Java的類上載涉及使用帶有引導,擴展程序和應用程序類負載器的分層系統加載,鏈接和初始化類。父代授權模型確保首先加載核心類別,從而影響自定義類LOA


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Dreamweaver Mac版
視覺化網頁開發工具