从0到实现SSM项目 Maven工程 day01

项目环境搭建(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";
	}
}
原创文章 36 获赞 8 访问量 2773

猜你喜欢

转载自blog.csdn.net/qq_41398619/article/details/105449055
今日推荐