Idea+maven搭建SSH(struts2+hibernate5+spring5)環(huán)境的方法步驟
最近要使用 SSH 來(lái)編寫(xiě)期末的考核任務(wù),之前也在網(wǎng)上查閱了很久,也試出了很多的問(wèn)題。也很感謝很多前輩們的總結(jié),我也查到了很多用用的內(nèi)容。
本次項(xiàng)目,我將以一個(gè)簡(jiǎn)單的登錄案例實(shí)現(xiàn) SSH 的項(xiàng)目整合,項(xiàng)目我會(huì)放到 Github 上面,需要的同學(xué)可以 clone 下來(lái)在本地跑一跑
項(xiàng)目地址:SSH 腳手架
一、項(xiàng)目環(huán)境搭建
使用 maven 搭建一個(gè) Java Web 項(xiàng)目
1.1 配置 Spring 坐標(biāo)依賴(lài)
引入 Spring 坐標(biāo)依賴(lài)
<!-- spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.0.RELEASE</version> </dependency> <!-- spring-web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.1.0.RELEASE</version> </dependency> <!--spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.1.0.RELEASE</version> </dependency> <!-- spring-orm --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>5.1.0.RELEASE</version> </dependency> <!-- aop面向切面依賴(lài)的jar包 --> <!-- aspectjrt --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.9.1</version> </dependency> <!-- aspectjweaver --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.1</version> </dependency>
1.2 配置 hibernate 坐標(biāo)依賴(lài)
我們的目標(biāo)是要整合 SSH,所以需要 hibernate 的核心依賴(lài), mysql 數(shù)據(jù)庫(kù)驅(qū)動(dòng),以及 c3p0 數(shù)據(jù)庫(kù)連接池
<!-- hibernate核心依賴(lài) --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.17.Final</version> </dependency> <!-- mysql數(shù)據(jù)庫(kù)驅(qū)動(dòng)依賴(lài) --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!-- c3p0連接池 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency>
1.3 配置 struts2 坐標(biāo)依賴(lài)
我們需要 struts 核心,以及 struts 整合 spring 的插件,以及 struts 對(duì) json 數(shù)據(jù)處理的插件
<!-- struts2 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.3.35</version> </dependency> <!-- struts2-spring-plugin整合spring和struts2 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.3.35</version> </dependency> <!-- json 數(shù)據(jù)處理,struts 插件 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-json-plugin</artifactId> <version>2.3.8</version> </dependency>
1.4 配置Java EE 坐標(biāo)依賴(lài)
這里可以引入 servlet api,jstl 標(biāo)簽庫(kù)等一系列工具
<!-- servlet api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> <scope>provided</scope> </dependency> <!-- lombok 一個(gè)插件,可以免 getter 和 setter 方法,但是需要我們?cè)?idea 中裝對(duì)應(yīng)的插件才可以使用,可以不要--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.0</version> <scope>provided</scope> </dependency> <!-- jstl --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency>
1.5 其他工具
json 處理工具
<dependency> <groupId>org.jetbrains</groupId> <artifactId>annotations-java5</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> <!-- 官方給的 json 包,建議使用這個(gè),但是我后面好像并沒(méi)有用到 --> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20160810</version> </dependency>
二、項(xiàng)目結(jié)構(gòu)搭建
2.1 配置文件
使用如下方式創(chuàng)建
1.applicationContext.xml
2.jdbc.properties
3.struts.xml
2.2 包結(jié)構(gòu)
創(chuàng)建如下的基本包結(jié)構(gòu)
三、編寫(xiě)配置文件
3.1 web.xml 文件配置
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <context-param> <param-name>contextConfigLocation</param-name> <!-- Spring 的配置文件--> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- struts2核心過(guò)濾器,過(guò)濾所有的請(qǐng)求 --> <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> <!-- 上下文監(jiān)聽(tīng)器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
3.2 編寫(xiě) jdbc.properties 文件
這里我們需要自己手動(dòng)修改數(shù)據(jù)庫(kù)的信息配置
jdbc.driverClass=com.mysql.jdbc.Driver jdbc.jdbcUrl=jdbc:mysql://localhost:3306/hibernate?characterEncoding=utf-8&autoReconnect=true&useSSL=false jdbc.user=root jdbc.password=root #連接池中保留的最小連接數(shù) jdbc.minPoolSize=1 #連接池中保留的最大連接數(shù) jdbc.maxPoolSize=20 #初始化連接數(shù) jdbc.initialPoolSize=1
3.3 編寫(xiě) applicationContext.xml 配置文件
這里面也包含了數(shù)據(jù)庫(kù)的基本配置
<?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: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/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 引入資源文件 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 自動(dòng)掃描與裝配bean--> <context:component-scan base-package="dao.*,service.*"/> <context:component-scan base-package="action"/> <!--引入注解解析器--> <context:annotation-config/> <!-- 數(shù)據(jù)源連接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driverClass}"/> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/> <property name="user" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> <property name="minPoolSize" value="${jdbc.minPoolSize}"/> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"/> <property name="initialPoolSize" value="${jdbc.initialPoolSize}"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <props> <!--配置Hibernate的方言--> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.current_session_context_class">thread</prop> <!--格式化輸出sql語(yǔ)句--> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.use_sql_comments">false</prop> </props> </property> <!-- 自動(dòng)掃描實(shí)體 --> <property name="packagesToScan" value="entity" /> </bean> <!-- 配置 HibernateTemplate 對(duì)象 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate"> <!-- 注入 SessionFactory 對(duì)象 --> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 用注解來(lái)實(shí)現(xiàn)事務(wù)管理 --> <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <tx:annotation-driven transaction-manager="txManager"/> </beans>
3.4 struts 配置文件
我們還沒(méi)有編寫(xiě)的具體的 action 服務(wù),所以這里先跳過(guò)
四、使用 hibernate 逆向生成工具生成實(shí)體
4.1 配置數(shù)據(jù)庫(kù)連接信息
使用 idea 自帶的數(shù)據(jù)庫(kù)連接的工具
完善基本配置信息
4.2 逆向生成實(shí)體類(lèi)
4.3 實(shí)體類(lèi)配置
生成好后可以看到和數(shù)據(jù)庫(kù)對(duì)應(yīng)的實(shí)體類(lèi),我的表很簡(jiǎn)單,一個(gè)簡(jiǎn)單的用戶(hù)表,只有 id, username, password 字段
但是我們發(fā)現(xiàn)里面的部分內(nèi)容會(huì)爆紅,這是因?yàn)槲覀儧](méi)有指定數(shù)據(jù)源
選擇我們剛才連接的數(shù)據(jù)庫(kù)
然后就沒(méi)問(wèn)題了。
五、JavaBean 編寫(xiě)
看到包結(jié)構(gòu),大家應(yīng)該可以猜出來(lái),我是使用的典型的 MVC 三層架構(gòu)來(lái)編寫(xiě)的
5.1 編寫(xiě) dao 層
創(chuàng)建 UserDao 以及 它的實(shí)現(xiàn)類(lèi) UserDaoImpl
UserDao 編寫(xiě)
package dao; import entity.User; public interface UserDao { // 用戶(hù)登錄驗(yàn)證 public User selectByUsernameAndPassword(String username, String password); }
UserDaoImpl
package dao.Impl; import dao.UserDao; import entity.User; import org.hibernate.Session; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate5.HibernateTemplate; import org.springframework.stereotype.Repository; import javax.annotation.Resource; // 使用 Spring 來(lái)接管持久層的所有操作 @Repository public class UserDaoImpl implements UserDao { // 使用 Hibernate 提供的模板 @Autowired @Resource private HibernateTemplate hibernateTemplate; // 生成對(duì)應(yīng)的 get 和 set 方法 public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } @Override public User selectByUsernameAndPassword(String username, String password) { // 登錄的邏輯不算難,就是使用 sql 語(yǔ)句查詢(xún),username 和 password 兩個(gè)字段是否存在即可,我們使用的是 hibernate 框架,所以要寫(xiě) hql 語(yǔ)句 Session session = hibernateTemplate.getSessionFactory().openSession(); Query q = session.createQuery("from User u where u.username = ? and u.password = ?"); q.setParameter(0,username); q.setParameter(1,password); User u = (User) q.uniqueResult(); return u; } }
我們寫(xiě)好了 dao 層,這時(shí)候發(fā)現(xiàn)出現(xiàn)了爆紅的問(wèn)題,這里我們需要手動(dòng)添加項(xiàng)目的依賴(lài)信息
點(diǎn)擊 project structure
添加這個(gè)就可以了,問(wèn)題就解決了
顯示正常了
5.2 編寫(xiě) Service 層
同樣,我們創(chuàng)建對(duì)應(yīng)的 UserService 和 對(duì)應(yīng)的 UserServiceImpl 類(lèi)
有的同學(xué)可能會(huì)問(wèn)道,不就是一個(gè)簡(jiǎn)單的登錄功能嘛,有必要這么麻煩嗎?是的,這么做確實(shí)沒(méi)必要,但是隨著項(xiàng)目的越來(lái)越大,只有把具體的功能全部分開(kāi)來(lái)做,這樣才不至于整個(gè)項(xiàng)目太過(guò)于亂
編寫(xiě)用戶(hù)的業(yè)務(wù)層 接口 UserService
package service; import entity.User; public interface UserService { // 登錄驗(yàn)證 User checklogin(String username, String password); }
編寫(xiě) 業(yè)務(wù)層對(duì)應(yīng)的實(shí)現(xiàn)類(lèi) UserServiceImpl
package service.Impl; import dao.UserDao; import entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import service.UserService; @Service public class UserServiceImpl implements UserService { // 這里業(yè)務(wù)層調(diào)用持久層的方法 @Autowired private UserDao ud; @Override public User checklogin(String username, String password) { return ud.selectByUsernameAndPassword(username,password); } }
5.3 編寫(xiě) Controller 層 (UserAction)
這里的邏輯思路,是 controller 層 調(diào)用 service 的方法,service 層調(diào)用 dao 層的方法
package action; import com.opensymphony.xwork2.ActionContext; import entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import service.UserService; import java.util.Map; // 使用 Controller 表示這是控制層,使用 ua 表示這個(gè)類(lèi)被 Spring 所管理 @Controller("ua") public class UserAction { // 編寫(xiě)兩個(gè)屬性,使用 struts2 的 ognl 表達(dá)式可以直接接收到前端穿過(guò)來(lái)的數(shù)據(jù),不再需要 request.getParameter("xxxx") 接收數(shù)據(jù)了 private String username; private String password; // 調(diào)用業(yè)務(wù)層的方法 @Autowired private UserService us; // get 方法可以不要, set 方法必須有,不然前端的數(shù)據(jù)就無(wú)法注入進(jìn)來(lái) 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; } // 編寫(xiě)登錄逇控制層方法 public String login() { System.out.println(username + " " + password); // 打印穿過(guò)來(lái)的數(shù)據(jù) ActionContext ac = ActionContext.getContext(); // 得到 servlet 中的三大域的 session 域,在這里我們要將數(shù)據(jù)保存至 session,并在前端展示 Map<String,Object> session = ac.getSession(); // 我們可以看到 session 的實(shí)質(zhì)就是一個(gè) map User user = us.checklogin(username,password); // 登錄驗(yàn)證 if ( user!=null ) { session.put("user",username); return "success"; } else { return "error"; } } }
5.4 編寫(xiě) struts 路由映射
記得在 Project Structure 添加如下配置
stucts 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="user" namespace="/" extends="struts-default"> <action name="checklogin" class="ua" method="login"> <!-- 登錄成功挑戰(zhàn)至首頁(yè) --> <result name="success" type="redirect">/index.jsp</result> <!-- 登錄失敗跳轉(zhuǎn)至錯(cuò)誤頁(yè)面 --> <result name="error" type="redirect">/error.jsp</result> </action> </package> </struts>
六、前端界面編寫(xiě)
6.1 登錄界面編寫(xiě)
<%-- Created by IntelliJ IDEA. User: Gorit Date: 2020/6/13 Time: 23:18 Contact: gorit@qq.com To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="checklogin" method="post"> <label for="username">賬戶(hù):</label> <input type="text" name="username" id="username"><br> <label for="password">密碼:</label> <input type="password" name="password" id="password"><br> <input type="submit" value="登錄"> </form> </body> </html>
6.1 登錄成功
<%-- Created by IntelliJ IDEA. User: Gorit Date: 2020/6/13 Time: 23:21 Contact: gorit@qq.com To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> <h3>歡迎你 ${sessionScope.user} 登錄!!</h3> </body> </html>
6.3 登錄失敗
<%-- Created by IntelliJ IDEA. User: Gorit Date: 2020/6/13 Time: 23:21 Contact: gorit@qq.com To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h2>出錯(cuò)啦?。?!</h2> </body> </html>
到此這篇關(guān)于Idea+maven搭建SSH(struts2+hibernate5+spring5)環(huán)境的方法步驟的文章就介紹到這了,更多相關(guān)Idea+maven搭建SSH內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MyBatis中執(zhí)行相關(guān)SQL語(yǔ)句的方法
本文主要介紹了MyBatis中執(zhí)行相關(guān)SQL語(yǔ)句的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-08-08Java多線(xiàn)程之條件對(duì)象Condition
這篇文章主要介紹了Java多線(xiàn)程之條件對(duì)象Condition,Condition中的await()方法相當(dāng)于Object的wait()方法,Condition中的signal()方法相當(dāng)于Object的notify()方法,Condition中的signalAll()相當(dāng)于Object的notifyAll()方法,接下來(lái)和小編一起進(jìn)入文章了解更具體的內(nèi)容2021-10-10詳解基于MybatisPlus兩步實(shí)現(xiàn)多租戶(hù)方案
這篇文章主要介紹了詳解基于MybatisPlus兩步實(shí)現(xiàn)多租戶(hù)方案,本文分兩步,通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04全面詳解java代碼重構(gòu)與設(shè)計(jì)模式
這篇文章主要為大家介紹了全面詳解java代碼重構(gòu)與設(shè)計(jì)模式的全面詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06Java編程中利用InetAddress類(lèi)確定特殊IP地址的方法
這篇文章主要介紹了Java編程中利用InetAddress類(lèi)確定特殊IP地址的方法,InetAddress類(lèi)是Java網(wǎng)絡(luò)編程中一個(gè)相當(dāng)實(shí)用的類(lèi),需要的朋友可以參考下2015-11-11Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁(yè)效果(實(shí)例代碼)
這篇文章主要介紹了Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁(yè)效果,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-02-02Java:com.netflix.client.ClientException錯(cuò)誤解決
本文主要介紹了Java:com.netflix.client.ClientException錯(cuò)誤解決,主要是指出客戶(hù)端?module-sso?試圖通過(guò)負(fù)載均衡器訪(fǎng)問(wèn)服務(wù)時(shí),負(fù)載均衡器沒(méi)有找到可用的服務(wù)器來(lái)處理請(qǐng)求,下面就來(lái)介紹一下解決方法2024-08-08Lucene實(shí)現(xiàn)多種高級(jí)搜索形式
這篇文章主要介紹了Lucene實(shí)現(xiàn)多種高級(jí)搜索形式的相關(guān)資料,需要的朋友可以參考下2017-04-04