MyEclipse整合ssh三大框架環(huán)境搭載用戶注冊源碼下載
前言
SSH不是一個框架,而是多個框架(struts+spring+hibernate)的集成,是目前較流行的一種Web應(yīng)用程序開源集成框架,用于構(gòu)建靈活、易于擴展的多層Web應(yīng)用程序。
集成SSH框架的系統(tǒng)從職責上分為四層:表示層、業(yè)務(wù)邏輯層、數(shù)據(jù)持久層和域模塊層(實體層)。
Struts作為系統(tǒng)的整體基礎(chǔ)架構(gòu),負責MVC的分離,在Struts框架的模型部分,控制業(yè)務(wù)跳轉(zhuǎn),利用Hibernate框架對持久層提供支持。Spring一方面作為一個輕量級的IoC容器,負責查找、定位、創(chuàng)建和管理對象及對象之間的依賴關(guān)系,另一方面能使Struts和Hibernate更好地工作。
使用MyEclipse整合SSH三大框架,并實現(xiàn)一個模擬用戶注冊的Demo,對應(yīng)版本:
Struts版本:2.1;
Spring版本:3.1;
Hibernate版本:3.3;
一、整合前準備工作
1.建立一個Web項目,如下:

注意:支持action的包名必須是“action”,且action類必須是以Action結(jié)尾,即形如XxxAction這種形式,如上圖中所示
2.創(chuàng)建數(shù)據(jù)庫以及表:
CREATE DATABASE sshdemo; CREATE table t_user( id INT PRIMARY KEY, username VARCHAR(10), password VARCHAR(20) )
3.導(dǎo)入數(shù)據(jù)庫連接池c3p0jar包,點擊可下載:
c3p0-0.9.2-pre1.jar、mysql-connector-java-5.1.13-bin.jar
二、Struts框架的配置:
1.選中項目,右鍵選擇:MyEclipse -> Project Facets[Capabilities] -> Install Apache Struts (2.x) Facet,如下:

2.選擇版本,在這里我選擇的是2.1,點擊"Finish",如下:

3.完成上述步驟以后,會發(fā)現(xiàn)在src目錄下多出一個struts.xml 文件,內(nèi)容如下:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> </struts>
4.在WEB-INF目錄下的web.xml文件中多一段關(guān)于struts過濾器的配置代碼,如下:

5.參考上圖,將*.action修改為"/*",至此struts框架配置完畢;
三、Spring框架的配置:
1.參考struts的配置,選中項目,右鍵選擇:MyEclipse -> Project Facets[Capabilities] -> Install Spring Facet,選擇版本,在此選擇3.1如下:

2.點擊"Finish",會發(fā)現(xiàn)src目錄下多了一個applicationContext.xml文件,WEB-INF目錄下多了一個spring-form.tld與spring.tld文件,并且在web.xml文件中多了一段與spring配置有關(guān)的代碼,spring框架搭建基本完畢(引入命名空間會在后面講到),如下所示:

四、Hibernate框架的配置:
1.參考struts的配置,選中項目,右鍵選擇:MyEclipse -> Project Facets[Capabilities] -> Install HibernateFacet,選擇版本,在此選擇3.3如下:

2.點擊"Finish",會發(fā)現(xiàn)src目錄下多了一個缺省包(可以刪除),并且在web.xml文件中多了一段代碼(后面會重新配置),如下所示:

3.支持“@Entity”注解的jar包導(dǎo)入:選中項目,右鍵選擇:MyEclipse -> Project Facets[Capabilities] ->Manage...,然后照下圖中的步驟操作:

完成上述步驟,三大框架基本就搭建起來了,接下來整合它們。
五、整合
1.為了不讓applicationContext.xml看起來太臃腫,以及便于管理,我們將Hibernate有關(guān)的配置保存在另外一個.xml文件中,然后再在applicationContext.xml導(dǎo)入,其具體步驟:
(1)在src目錄下(與applicationContext.xml同級)創(chuàng)建一個名為hibernateContext.xml的文件,復(fù)制applicationContext.xml里面的內(nèi)容,然后再做修改;
(2)hibernateContext.xml文件里面的內(nèi)容:
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <!-- sessionFactory 配置 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <!-- dataSource的屬性會在applicationContext.xml文件中配置,在這里先引用 --> <property name="dataSource" ref="dataSource"></property> <!-- 設(shè)置hibernate相關(guān)的配置項 --> <property name="hibernateProperties"> <!-- props標簽是為了注入Properties這個類型的屬性 --> <!-- key必須加上hibernate.前綴 --> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <!-- show_sql目的是打印sql語句 --> <prop key="hibernate.show_sql">true</prop> <!-- 美化SQL的打印格式 --> <prop key="hibernate.format_sql">true</prop> <!-- a) create-drop:在執(zhí)行程序的時候創(chuàng)建數(shù)據(jù)表,在執(zhí)行完了之后刪除表,實際開發(fā)中,常用于測試 b) create:在每次執(zhí)行程序的時候重新創(chuàng)建數(shù)據(jù)表 c) update:在執(zhí)行程序的時候會判斷,如果存在,不創(chuàng)建表,否則創(chuàng)建數(shù)據(jù)表,并且會根據(jù)實體類中的屬性的增加,而自動增加數(shù)據(jù)表中的字段(開發(fā)環(huán)境) d) validate:在執(zhí)行程序的時候會判斷,如果實體類中的屬性與表中的字段不一致,那么就報錯(生產(chǎn)環(huán)境) --> <prop key="hibernate.hbm2ddl.auto">validate</prop> </props> </property> <!-- 配置hibernate的實體類 --> <property name="packagesToScan"> <!--list標簽是用來注入String[]類型的屬性 ,其值一般是對應(yīng)的bean包的全限名,而bean包中的類一般又是與數(shù)據(jù)庫中的表對應(yīng)--> <list> <value>com.beauxie.bean</value> </list> </property> </bean> <!-- 配置 hibernateTemplate模板 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> </beans>
(3)在applicationContext.xm刪除“sessionFactory”的配置(因為在hibernateContext.xml中已經(jīng)配置好了),然后導(dǎo)入已經(jīng)修改好的hibernateContext.xml內(nèi)容,導(dǎo)入完以后,此時applicationContext.xml內(nèi)容如下:
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> </bean> <!-- 導(dǎo)入其他的spring配置文件 ,如果都放在一個文件里,會看起來比較臃腫--> <import resource="hibernateContext.xml"/> </beans>
2.在applicationContext.xm文件中原先dataSource的基礎(chǔ)上,修改其配置(數(shù)據(jù)庫名、用戶名、密碼等),(注意:value標簽中一定不能含有空格、回車??!),如下所示:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl"> <!--如果直接用value屬性,而不用value標簽,則需要將“&”轉(zhuǎn)義(&) ,用value標簽,<span style="color:#FF0000;">標簽中一定不能含有空格、回車,因為它會將空格轉(zhuǎn)換成" "</span>,導(dǎo)致數(shù)據(jù)庫會連接不上,除非重寫數(shù)據(jù)源 --> <value><![CDATA[jdbc:mysql://localhost:3306/sshdemo?useUnicode=true&characterEncoding=UTF8&useServerPrepStmts=true&prepStmtCacheSqlLimit=256&cachePrepStmts=true&prepStmtCacheSize=256&rewriteBatchedStatements=true]]></value> </property> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="user" value="root"></property> <property name="password" value="root"></property> <property name="acquireIncrement" value="3"></property> <property name="initialPoolSize" value="10"></property> <property name="minPoolSize" value="2"></property> <property name="maxPoolSize" value="10"></property> </bean>
3.在applicationContext.xm中,配置spring的掃描器,這樣給我們的類加上spring組件注解,就可以實現(xiàn)bean的自動載入,具體步驟如下:(1)引入context命名空間,支持context標簽,點擊底部的"Namespaces",然后勾選context那一項即可:

(2)配置spring掃描器:
<!-- 配置spring的掃描器,然后給我們的類加上spring組件注解,就可以實現(xiàn)bean的自動載入-->
<context:component-scan base-package="com.beauxie.action,com.beauxie.service,com.beauxie.dao">
</context:component-scan>
至此ssh三大框架環(huán)境搭建完畢,接下來是在ssh框架基礎(chǔ)上實現(xiàn)用戶注冊
六、案例:簡單的模仿用戶注冊
1.前臺注冊頁面代碼,index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>歡迎注冊</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="${pageContext.request.contextPath }/user/regist" method="POST">
<!-- 也可以使用user.username自動裝入user屬性,但在這里不是重點,所以就在后臺手動獲取其值-->
用戶名:<input type="text" name="username"><br> 密
碼:<input type="password" name="password"><br>
<input type="submit" value="注冊">
</form>
</body>
</html>
2.User類代碼:
package com.beauxie.bean;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author Beauxie
* 在這里User的屬性應(yīng)當與t_user表中的字段相同,
* 否則就需要手動為不相同的屬性指定對應(yīng)表中的字段
*/
@Entity//映射數(shù)據(jù)庫表
@Table(name="t_user")//不加這個注解,默認對應(yīng)的是user表
public class User {
@Id//對應(yīng)t_user表中的主鍵
private int id;//用戶ID
private String username;//用戶名
private String password;//密碼
public int getId() {
return id;
}
public void setId(int 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;
}
}
3.UserDao類代碼:
package com.beauxie.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.beauxie.bean.User;
/**
* @author Beauxie
* Dao層,對數(shù)據(jù)庫進行操作
*/
@Repository//這個屬性對應(yīng)的是持久層(一般為Dao層),說明交給spring管理,而對應(yīng)的包下的類名也會有一個"S"
public class UserDao {
@Autowired//自動注入,不需要設(shè)值,因為在spring配置文件中已經(jīng)配置過
private HibernateTemplate template;
/**
* 用戶注冊,即向表中添加一條新的記錄
* @param user
*/
public void addUser(User user){
//往數(shù)據(jù)庫中添加一條數(shù)據(jù),一句話就可以搞定
template.save(user);
}
}
4.UserService類代碼:
package com.beauxie.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.beauxie.bean.User;
import com.beauxie.dao.UserDao;
/**
* @author Beauxie
* Service層
*/
@Service//這個屬性對應(yīng)的是業(yè)務(wù)層一般為Service層),說明交給spring管理,而對應(yīng)的包下的類名也會有一個"S"
public class UserService {
@Autowired//同樣是自動注入
private UserDao userDao;
public void addUser(User user){
//調(diào)用Dao層的addUser方法
userDao.addUser(user);
}
}
5.UserAction類代碼:
package com.beauxie.action;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.beauxie.bean.User;
import com.beauxie.service.UserService;
/**
* @author Beauxie
*
*/
@Controller//用于標注控制層組件
@Namespace("/user")//url前綴
@Scope("prototype")//Action默認是單例,但實際開發(fā)中,一般是多例,因為一般一個Action可能會對應(yīng)多個不同的請求
//@ParentPackage("struts-default")//繼承特定的package,默認是“struts-default”,因此可以省略不寫
@Results({
@Result(name="registSuccess",location="/msg.jsp")
})
public class UserAction {
@Autowired//自動注入
private UserService service ;
//struts默認攔截“.action以及不加任何后綴”
@Action(value="regist")//訪問:/user/regist.action 或 /user/regist
public String regist(){
//獲取request
HttpServletRequest request = ServletActionContext.getRequest();
//獲取表單提交的數(shù)據(jù)
String username = request.getParameter("username");
String password = request.getParameter("password");
//封裝userBean
User user = new User();
user.setId(1000);
user.setUsername(username);
user.setPassword(password);
//調(diào)用service層的方法,向數(shù)據(jù)庫中增加一條記錄
service.addUser(user);
//將提示信息存入request域中,用以前臺顯示
request.setAttribute("msg", "恭喜您,注冊成功!<br>注冊名:"+username);
return "registSuccess";
}
}
6.消息提示界面:msg.jsp代碼,如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>消息提示</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
${msg }
</body>
</html>
7.將項目添加到服務(wù)器中,啟動服務(wù),打開瀏覽器,訪問:http://localhost/SSHDemo/user/regist

8.輸入用戶名與密碼,點擊“注冊”,顯示結(jié)果:

9.控制臺輸出sql語句(在hibernateContext.xml文件中已經(jīng)配置過輸出并美化SQL語句):

10.查看數(shù)據(jù)庫結(jié)果:

到此這個簡單的案例就已經(jīng)結(jié)束了,關(guān)于表單提交數(shù)據(jù)校驗、以及亂碼問題并未涉及,后續(xù)應(yīng)該會更新吧、、、
七、總結(jié):
1.三大框架的整合,應(yīng)該先引入每個框架以后,再整合;
2.一定要記得導(dǎo)入數(shù)據(jù)庫jar包;
3.Action類應(yīng)該要放在包名為"action"的包下,并且類名應(yīng)當要以Action結(jié)尾,形如“XxxAction”;
4.在配置Hibernate時,一定要導(dǎo)入支持“@Entity”注解的jar包;
5.可以再struts.xml文件中定義struts攔截的請求類型,默認為.action與不加后綴
6.可以再web.xml文件中定義struts過濾器的過濾類型,默認為*.action,應(yīng)當改為/*;
7.在applicationContext.xm文件中需要配置:sessionFactory、hibernate的實體類、hibernateTemplate模板 、數(shù)據(jù)源dataSource、spring掃描器五部分(包含hibernateContext.xml);
8.各個類中一定要加上對應(yīng)的注解,以及Action中的方法上也要加注解。
實例源碼下載:http://xiazai.jb51.net/201610/yuanma/SSHzhuce(jb51.net).rar
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
IntelliJ IDEA 2021.1 首個 Beta 版本發(fā)布
這篇文章主要介紹了IntelliJ IDEA 2021.1 首個 Beta 版本發(fā)布,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03
Java注解之Retention、Documented、Inherited介紹
這篇文章主要介紹了Java注解之Retention、Documented、Inherited注解介紹,本文內(nèi)容和相關(guān)文章是系列文章,需要的朋友可以參考下2014-09-09
Java數(shù)據(jù)結(jié)構(gòu)之隊列(動力節(jié)點Java學(xué)院整理)
隊列(Queue)是只允許在一端進行插入,而在另一端進行刪除的運算受限的線性表。 這篇文章詳細給大家介紹了java數(shù)據(jù)結(jié)構(gòu)之隊列,感興趣的朋友跟隨小編一起學(xué)習(xí)吧2017-04-04
解決SpringBoot 測試類無法自動注入@Autowired的問題
這篇文章主要介紹了解決SpringBoot 測試類無法自動注入@Autowired的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03

