項目環境搭建(SSM整合)
一項目環境搭建
1導入數據庫
-- --------------------------------------------
-- 創建yonghedb庫、tb_door、tb_order表並插入記錄
-- --------------------------------------------
-- set names gbk; ##設置編碼
-- 刪除yonghedb庫(如果存在)
-- drop database if exists yonghedb;
-- 重新創建yonghedb庫
create database if not exists yonghedb charset utf8;
-- 選擇yonghedb庫
use yonghedb;
-- 刪除門店表(需要先刪除訂單表)
drop table if exists tb_order;
drop table if exists tb_door;
-- 創建門店表
create table tb_door(
id int primary key auto_increment, -- 門店id
name varchar(100), -- 門店名稱
tel varchar(100), -- 聯繫電話
addr varchar(255) -- 門店地址
);
-- 往門店表中插入記錄
insert into tb_door values ('1', '永和大王(北三環西路店)', '010-62112313', '北三環西路甲18號院-1號大鐘寺中坤廣場d座');
insert into tb_door values ('2', '永和大王(知春路店)', '010-82356537', '知春路29號大運金都');
insert into tb_door values ('3', '永和大王(東直門)', '010-84477746', '東直門外大街48號東方銀座b2-08');
insert into tb_door values ('4', '永和大王(北京站)', '010-65286602', '毛家灣衚衕甲13號北京站候車大廳2層');
insert into tb_door values ('5', '永和大王(學院路店)', '010-62152539', '學院南路37號超市發四道口店四道口西北角');
-- 刪除訂單表(如果存在)
drop table if exists tb_order;
-- 創建訂單表
create table tb_order(
id int(11) primary key AUTO_INCREMENT, -- 訂單id
door_id int(11), -- 門店id
order_no varchar(50), -- 訂單編號
order_type varchar(50), -- 訂單類型(堂食/打包/外賣..)
pnum int, -- 用餐人數
cashier varchar(50), -- 收銀員
order_time timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', -- 下單時間
pay_time timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', -- 支付時間
pay_type varchar(50), -- 支付類型(微信支付/支付寶支付)
price double, -- 支付金額
foreign key(door_id) REFERENCES tb_door(id) -- 關聯外鍵
-- on update cascade -- 級聯更新
-- on delete cascade -- 級聯刪除
);
-- 往訂單表中插入記錄
INSERT INTO tb_order VALUES ('1', '1', 'P001', '堂食', '1', '張三', '2018-04-26 14:49:07', '2018-04-26 14:50:38', '微支付', '16.00');
INSERT INTO tb_order VALUES ('2', '1', 'P003', '外賣', '3', '張三', '2018-04-27 13:34:07', '2018-04-27 13:34:38', '微支付', '20.00');
INSERT INTO tb_order VALUES ('3', '1', 'P005', '打包', '1', '張三', '2019-01-22 11:59:22', '2019-01-22 11:59:22', '微支付', '28.00');
INSERT INTO tb_order VALUES ('4', '1', 'P007', '堂食', '1', '李四', '2019-01-23 13:01:26', '2019-01-23 13:01:26', '微支付', '49.00');
2.創建Maven的簡單web工程(yonghe-ssm)
2.1補全WEB-INF目錄和web.xml文件
3.創建包路徑和目錄
src/main/java
com.tedu.controller
com.tedu.service
com.tedu.dao
com.tedu.pojo
src/main/resource
mybatis
mapper
spring
src/main/webapp/WEB-INF
pages
test.jsp
4.在pom.xml文件中,引入junit、log4j、servlet等依賴包
<dependencies>
<!-- 單元測試 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!-- 整合log4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
<!-- Jackson Json處理工具包 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.2</version>
</dependency>
<!-- Servlet/JSP/JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
5.在resources目錄下創建log4j.properties文件,配置內容如下:
log4j.properties用來打印日誌文件,能更好觀察成勳運行流程
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] %m%n
二.整合spring框架
1、在pom.xml文件中,引入spring的依賴包
<!-- 整合spring框架(包含springmvc)
這個jar文件包含springmvc開發時的核心類, 同時也會將依賴的相關jar文件引入進來(spring的核心jar文件也包含在內)
-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<!--這個jar文件包含對Spring對JDBC數據訪問進行封裝的所有類 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
2、在resources/spring目錄下,創建spring的核心配置文件:applicationContext.xml
配置內容如下
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
</beans>
三.整合springmvc框架
1.在resources/spring目錄下,創建springmvc的核心配置文件:springmvc-config.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 1.配置前端控制器放行靜態資源(html/css/js等,否則靜態資源將無法訪問) -->
<mvc:default-servlet-handler/>
<!-- 2.配置註解驅動,用於識別註解(比如@Controller) -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 3.配置需要掃描的包:spring自動去掃描 base-package 下的類,
如果掃描到的類上有 @Controller、@Service、@Component等註解,
將會自動將類註冊爲bean
-->
<context:component-scan base-package="com.tedu.controller">
</context:component-scan>
<!-- 4.配置內部資源視圖解析器
prefix:配置路徑前綴
suffix:配置文件後綴
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
2、在web.xml中配置springmvc
<!-- 配置springmvc, 將所有請求交給springmvc來處理 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置springmvc核心配置文件的位置,默認Springmvc的配置文件是在WEB-INF目錄下,默認的名字爲springmvc-servlet.xml,如果要放在其他目錄,則需要指定如下配置:
-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/*.xml</param-value>
</init-param>
</servlet>
<!-- 其中的斜槓(/)表示攔截所有請求(除JSP以外), 所有請求都要經過springmvc前端控制器 -->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
3、web.xml繼續配置springmvc亂碼處理過濾器
<!-- 亂碼處理過濾器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- 指定編碼集 -->
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<!-- 指定攔截方式爲攔截所有請求 -->
<url-pattern>/*</url-pattern>
</filter-mapping>
4、測試springmvc框架:
(1)創建test.jsp頁面
在WEB-INF/pages/目錄下,創建test.jsp頁面。
<%@ page pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<h1>test springmvc~~~</h1>
</body>
</html>
(2)創建測試Controller: TestController`
/*@Controller:(1)表示當前類屬於controller層
* 標識當前類的對象的創建由spring容器負責
*/
/** 測試類:測試springmvc開發環境 */
@Controller
public class TestController {
@RequestMapping("/hello")
public String hello(){
return "test"; //跳轉到test.jsp界面
}
}
(3)將項目部署到服務器中,啓動服務器:
注意:在項目直接點運行到服務器會報404,
因爲controller類不是jsp也不是servlet不能直接在服務器運行
需要在項目網址後加上方法中@RequestMapping的路徑 /hello
直接運行項目的網址:http://localhost:8080/yonghe-ssm
加上/hello後 --------> http://localhost:8080/yonghe-ssm/hello
如果瀏覽器顯示test.jsp的內容說明配置成功.
四.整合mybatis框架
1.在pom.xml文件中,引入mybatis及相關依賴包
<!-- 整合mybatis框架 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- mysql驅動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<!-- druid連接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
2.在resources/mybatis目錄下,創建mybatis的核心配置文件:mybatis-config.xml
注意數據庫配置密碼是否正確
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- MyBatis的全局配置文件 -->
<configuration >
<!-- 1.配置開發環境 -->
<environments default="develop">
<!-- 這裏可以配置多個環境,比如develop,test等 -->
<environment id="develop">
<!-- 1.1.配置事務管理方式:JDBC:將事務交給JDBC管理(推薦) -->
<transactionManager type="JDBC"></transactionManager>
<!-- 1.2.配置數據源,即連接池方式:JNDI/POOLED/UNPOOLED -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/yonghedb?characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 2.加載Mapper配置文件,路徑以斜槓間隔: xx/xx/../xx.xml -->
<mappers>
<mapper resource="mybatis/mapper/DoorMapper.xml"/>
</mappers>
</configuration>
3.在pojo包中創建實體類Door,用於封裝所有的門店信息
package com.tedu.pojo;
public class Door {
private Integer id; //門店編號
private String name; //門店名稱
private String tel; //門店電話
private String addr; //門店地址
//getter和setter方法
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
//重寫toString方法
@Override
public String toString() {
return "Door [id=" + id + ", name=" + name + ", tel=" + tel + ", addr=" + addr + "]";
}
}
4.在src/main/resources/mybatis/mapper目錄下,創建Door實體類的映射文件—DoorMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 門店表的映射文件 namespace值爲對應接口的全路徑 -->
<mapper namespace="com.tedu.dao.DoorMapper">
<!-- 1.查詢所有門店信息,id值爲對應接口中方法的名字
resultType指定將查詢的結果封裝到哪個pojo對象中
-->
<select id="findAll" resultType="com.tedu.pojo.Door">
select * from tb_door
</select>
</mapper>
5.在mybatis的全局配置文件中引入DoorMapper.xml映射文件,第2步時已加內容
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- MyBatis的全局配置文件 -->
<configuration >
<!-- 1.配置開發環境 -->
...
<!-- 2.加載Mapper配置文件,路徑以斜槓間隔: xx/xx/../xx.xml -->
<!-- 配置映射文件 -->
<mappers>
<mapper resource="mybatis/mapper/DoorMapper.xml"/>
</mappers>
</configuration>
6.創建com.tedu.dao.DoorMapper接口,並根據EmpMapper.xml文件中的sql語句,提供findAll方法
package com.tedu.dao;
import java.util.List;
import com.tedu.pojo.Door;
/**
* DoorMapper接口
* 聲明增刪改查方法,對門店信息進行操作
*/
public interface DoorMapper {
/**
* 1.查詢所有門店信息
*/
public List<Door> findAll();
}
7.創建測com.tedu.controller.TestMybatis類,對mybatis開發環境進行測試
package com.tedu.controller;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.tedu.dao.DoorMapper;
import com.tedu.pojo.Door;
/** 測試類:測試mybatis開發環境 */
public class TestMybatis {
public static void main(String[] args) throws Exception {
//1.讀取mybatis-config.xml核心文件
InputStream in = Resources.getResourceAsStream(
"mybatis/mybatis-config.xml");
//2.獲取SqlSessionFactory工廠
SqlSessionFactory factory =
new SqlSessionFactoryBuilder()
.build(in);
//3.獲取SqlSession對象
SqlSession session = factory.openSession();
//4.獲取DoorMapper接口的實例
DoorMapper mapper = session.getMapper(DoorMapper.class);
//5.調用findAll方法查詢所有門店信息
List<Door> list = mapper.findAll();
//6.遍歷所有門店信息
for(Door door : list){
System.out.println(door);
}
}
}
執行結果:
打印數據庫中的表信息則成功.
五.整合spring和mybatis
防止整合出錯,可在整合前可以複製以分mybatis-config.xml文件爲mybatis-config2.xml
再把TestMybatis.java文件中
InputStream in = Resources.getResourceAsStream(
"mybatis/mybatis-config.xml");
//改爲下面這句,換個配置文件
InputStream in = Resources.getResourceAsStream(
"mybatis/mybatis-config2.xml");
然後在mybatis-config.xml中修改整合信息
1.修改mybatis-config.xml文件,將連接池等配置移除,在spring中配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- MyBatis的全局配置文件 -->
<configuration >
<!-- 1.配置開發環境 -->
<!-- 1.1.配置事務管理方式:JDBC:將事務交給JDBC管理(推薦) -->
<!-- 1.2.配置數據源,即連接池方式:JNDI/POOLED/UNPOOLED -->
<!-- 2.加載Mapper配置文件,路徑以斜槓間隔: xx/xx/../xx.xml -->
</configuration>
2.applicationContext.xml中配置druid連接池
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 1.加載jdbc.properties文件的位置 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 2.配置druid連接池 ,id是固定值,class是druid連接池類的全路徑 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<!-- 配置連接數據庫的基本信息 -->
<property name="driverClassName" value="${db.driverClassName}"></property>
<property name="url" value="${db.url}"></property>
<property name="username" value="${db.username}"></property>
<property name="password" value="${db.password}"></property>
</bean>
<!-- 3.整合spring和mybatis框架
將SqlSession等對象的創建交給Spring容器
id值(sqlSessionFactory)是固定值
-->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 3.1.指定mybatis核心配置文件的位置 -->
<property name="configLocation"
value="classpath:mybatis/mybatis-config.xml"></property>
<!-- 3.2.配置連接池(數據源) ref指向連接池bean對象的id值 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 3.3、掃描所有的 XxxMapper.xml映射文件,讀取其中配置的SQL語句 -->
<property name="mapperLocations" value="classpath:mybatis/mapper/*.xml"/>
</bean>
<!-- 4、定義mapper接口掃描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 掃描所有XxxMapper接口,將接口實例的創建交給spring容器 -->
<property name="basePackage"
value="com.tedu.dao"/>
</bean>
<!--本例中不涉及第五個 -->
<!-- 5.配置需要掃描的包(service層):spring自動去掃描 base-package下的類,
如果掃描到的類上有 @Controller、@Service、@Component等註解,
將會自動將類註冊爲bean(即由spring創建實例)
-->
<!-- <context:component-scan
base-package="com.tedu.service">
</context:component-scan> -->
</beans>
3.在resources目錄下創建jdbc.properties文件,將連接數據庫的基本信息提取到文件中
因爲mybatis配置文件mybatis-config.xml中獲取配置文件爲${jdbc.xxx},
而spring核心配置文件applicationContext.xml獲取配置文件信息爲${db.xxx},
所以把兩者加載數據信息都放在了配置文件
# TestMybatis
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/yonghedb?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
# applicationContext.xml
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql:///yonghedb?characterEncoding=utf-8
db.username=root
db.password=123456
4.在controller包下創建TestSSM類,測試是否整合成功
package com.tedu.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.tedu.dao.DoorMapper;
import com.tedu.pojo.Door;
/** 測試類:測試SSM開發環境 */
@Controller /* 這個註解表示當前類屬於Controller層代碼 */
public class TestSSM {
/** 自動裝配:由spring自動爲屬性賦值(對象)
* spring的核心配置穩文件中配置過自動掃描包,程序執行時,
* 框架底層會掃描所有mapper接口,爲接口提供提供子類並根據子類創建實例
* 即接口的子類實例,@Autowired可以根據接口的類型到spring容器中獲取
* 接口的子類實例,並賦值給dao
*
* */
@Autowired
private DoorMapper dao;
@RequestMapping("/testssm")
public String testSSM(){
//1.調用findAll方法查詢所有門店信息
List<Door> list = dao.findAll();
//2.遍歷所有門店信息
for(Door door : list){
System.out.println(door);
}
return "test";
}
}