框架的整合是将spring框架整合mybatis框架,spring框架整合springMVC框架,spring框架是灵魂框架,还可以整合第三方的框架。
下面介绍整合框架的步骤:
一、第一步,创建所需要的数据库和表(在这里省略)
例如:
这个是商品的表
create table PRODUCT
(
ID VARCHAR2(32) default SYS_GUID() not null,
PRODUCTNUM VARCHAR2(50) not null,
PRODUCTNAME VARCHAR2(50),
CITYNAME VARCHAR2(50),
DEPARTURETIME TIMESTAMP(6),
PRODUCTPRICE NUMBER,
PRODUCTDESC VARCHAR2(500),
PRODUCTSTATUS INTEGER
)
insert into PRODUCT (ID, PRODUCTNUM, PRODUCTNAME, CITYNAME, DEPARTURETIME, PRODUCTPRICE, PRODUCTDESC, PRODUCTSTATUS)
values ('676C5BD1D35E429A8C2E114939C5685A', 'itcast-002', '北京三日游', '北京', to_timestamp('10-10-2018 10:10:00.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 1200, '不错的旅行', 1);
insert into PRODUCT (ID, PRODUCTNUM, PRODUCTNAME, CITYNAME, DEPARTURETIME, PRODUCTPRICE, PRODUCTDESC, PRODUCTSTATUS)
values ('12B7ABF2A4C544568B0A7C69F36BF8B7', 'itcast-003', '上海五日游', '上海', to_timestamp('25-04-2018 14:30:00.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 1800, '魔都我来了', 0);
insert into PRODUCT (ID, PRODUCTNUM, PRODUCTNAME, CITYNAME, DEPARTURETIME, PRODUCTPRICE, PRODUCTDESC, PRODUCTSTATUS)
values ('9F71F01CB448476DAFB309AA6DF9497F', 'itcast-001', '北京三日游', '北京', to_timestamp('10-10-2018 10:10:00.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 1200, '不错的旅行', 1);
commit;
二、第二步,创建项目所需要的各个模块
三、第三步,[创建maven的web工程所需要的jar包,参考这个链接]
(https://blog.csdn.net/qq_38313060/article/details/82957218)
这个坐标是在父工程里面的pom.xml文件中导入的,里面有需要的坐标,太多了,就不在写了。
四、第四步,编写代码
4.1、编写domain模块中的代码(此处省略)
例如:编写一个 Product 商品的实体类
public class Product{
private String id; // 主键
private String productNum; // 编号 唯一
private String productName; // 名称
private String cityName; // 出发城市
//@DateTimeFormat(pattern="yyyy-MM-dd HH:mm")
private Date departureTime; // 出发时间
private String departureTimeStr;
private double productPrice; // 产品价格
private String productDesc; // 产品描述
private Integer productStatus; // 状态 0 关闭 1 开启
private String productStatusStr;
//此处省略了get和set方法,可以在这个类里面按 Alt+insert 快捷键选择生成set和get方法
}
4.2、编写 dao 模块中代码
4.2.1、编写dao接口
例如:
public interface IProductDao {
//查询所有的商品信息
@Select("select * from product")
public List<Product> findAll() throws Exception;
}
4.2.2、编写dao层配置文件,mybatis配置文件
例如:applicationContext-dao.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: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/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--dao层配置文件开始-->
<!--添加db.properties文件的加载 -->
<context:property-placeholder location="classpath:db.properties"/>
<!--配置连接池 使用C3p0连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置生产SqlSession对象的工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--扫描pojo包,给包下所有pojo对象起别名-->
<property name="typeAliasesPackage" value="com.itheima.ssm.domain"/>
<!--添加 pagehelper 插件 mybatis中的分页的插件-->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<!--使用下面的方式配置参数,一行配置一个 -->
<props>
<!--这个是选择使用的那个数据库-->
<prop key="helperDialect">oracle</prop>
<!--这个是当查询的时候的数据,当页数小于1页的时候显示的是第一页的数据,或者当大于总的页数的时候,显示的是最大页数-->
<prop key="reasonable">true</prop>
</props>
</property>
</bean>
</array>
</property>
</bean>
<!--扫描接口包路径,生成包下所有接口的代理对象,并且放入spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.itheima.ssm.dao"/>
</bean>
<!--dao层配置文件结束-->
</beans>
db.properties 的配置文件的代码如:
这个是oracle的配置
jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@127.0.0.1:1521:xe
jdbc.username=ssm
jdbc.password=123456
4.2.3、编写测试代码
用途是:看配置是否成功,方便后面代码的编写,也方便后面出错,好找错误,不过这个不是必需的。
代码如下:
public class ProductTest {
private IProductDao productDao;
@Before
public void init(){
ApplicationContext ca = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
productDao = ca.getBean(IProductDao.class);
}
@Test
public void findAll() throws Exception {
System.out.println("sfsfs");
List<Product> all = productDao.findAll();
System.out.println(all);
}
}
4.3、编写业务逻辑层(service)
4.3.1、编写业务逻辑层的接口和实现类
编写接口例如:
public interface IProductService {
//查询所有的商品信息 未分页
public List<Product> findAll() throws Exception;
}
编写实现代码如下:
@Service //这个注解是将这个实现类交给spring容器进行管理
@Transactional //这个注解是开事务
public class ProductServiceImpl implements IProductService {
@Autowired //这个注解是将IProductDao 接口创建出来,相当于创建了这个接口的实现类,可以调用其中的方法
private IProductDao productDao;
//查询所有的商品信息 没有分页
@Override
public List<Product> findAll() throws Exception {
return productDao.findAll();
}
}
4.3.2、编写配置文件
applicationContent_service.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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--service层配置文件开始-->
<!--组件扫描配置-->
<context:component-scan base-package="com.itheima.ssm.service"/>
<!--aop面向切面编程,切面就是切入点和通知的组合-->
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务的通知-->
<tx:advice id="advice">
<!--配置事务的属性-->
<tx:attributes>
<!--下面这个配置是将 带有find开头的方法设置为只读的方式-->
<tx:method name="find*" read-only="true"/>
<!--下面都是采用默认的方式-->
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置切面-->
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.itheima.ssm.service.impl.*.*(..))"/>
<aop:advisor advice-ref="advice" pointcut-ref="pointcut"/>
</aop:config>
<!--service层配置文件结束-->
<!--这个配置是将dao层中的配置文件 applicationContext-dao.xml 引入到这个 service 层中 方便引用mybatis中的方法-->
<import resource="applicationContext.xml"/>
</beans>
4.3.3、编写业务逻辑层(service)的测试代码
作用和dao层的测试代码一样,不过这个不是必需的
public class ProductsTest {
private IProductService productService;
@Before
public void init(){
ApplicationContext ac = new ClassPathXmlApplicationContext("spring/applicationContent_service.xml");
productService = ac.getBean(IProductService.class);
}
@Test
public void testProduct() throws Exception {
List<Product> products = productService.findAll();
System.out.println(products);
}
}
4.4、编写表现层(web)代码
这一层创建的是一个maven的web层的项目
4.4.1、编写webapp文件夹下的WEB-INF文件夹下的web.xml配置文件
这个配置文件里面有
(1)配置中文乱码的过滤器
(2)配置spring核心监听器,作用是加载spring的配置文件,这里是service层的配置文件,,但是service层的配置文件里面加入了dao层的配置文件,所以只需要加载service层的配置文件即可
(3)配置前端控制器
<!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 xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!--编码过滤器-->
<filter>
<filter-name>encoding</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置spring核心监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--重新指定spring配置文件的路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContent_service.xml</param-value>
</context-param>
<!--springmvc的核心servlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
4.4.2、配置web层的配置文件 springMVC.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--组件扫描-->
<context:component-scan base-package="com.itheima.ssm.web"/>
<!--处理器映射器,处理器适配器-->
<!-- 修改<mvc:annotation-driven>标签让自定义转换器生效-->
<mvc:annotation-driven conversion-service="conversionService">
<mvc:message-converters>
<!-- 指定springmvc json转换工具包使用fastjson -->
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"></bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!--视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--释放静态资源-->
<mvc:default-servlet-handler/>
<!--配置自定义转换器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.itheima.ssm.utils.DateConverter"></bean>
</set>
</property>
</bean>
</beans>
4.4.3、编写JSP界面,还有CSS/js的资源
文件此处省略
这个是商品数据的展示的代码,直接到任意一个JSP页面都可以,如果没有CSS和js只是没有样式,不影响结果
这个界面是放在pages问价下的,如果不在这里,servlet中的代码展示数据的时候会找不到界面,会报错,原因是在springMVC中配置的结果。
product-list.jsp
<table id="dataList"
class="table table-bordered table-striped table-hover dataTable">
<thead>
<tr>
<th class="" style="padding-right: 0px;"><input
id="selall" type="checkbox" class="icheckbox_square-blue">
</th>
<th class="sorting_asc">ID</th>
<th class="sorting_desc">编号</th>
<th class="sorting_asc sorting_asc_disabled">产品名称</th>
<th class="sorting_desc sorting_desc_disabled">出发城市</th>
<th class="sorting">出发时间</th>
<th class="text-center sorting">产品价格</th>
<th class="sorting">产品描述</th>
<th class="text-center sorting">状态</th>
<th class="text-center">操作</th>
</tr>
</thead>
<tbody>
<c:forEach items="${productList}" var="product">
<tr>
<td><input name="ids" type="checkbox"></td>
<td>${product.id }</td>
<td>${product.productNum }</td>
<td>${product.productName }</td>
<td>${product.cityName }</td>
<td>${product.departureTimeStr }</td>
<td class="text-center">${product.productPrice }</td>
<td>${product.productDesc }</td>
<td class="text-center">${product.productStatusStr }</td>
<td class="text-center">
<button type="button" class="btn bg-olive btn-xs">订单</button>
<button type="button" class="btn bg-olive btn-xs">详情</button>
<button type="button" class="btn bg-olive btn-xs">编辑</button>
</td>
</tr>
</c:forEach>
</tbody>
<!--
<tfoot>
<tr>
<th>Rendering engine</th>
<th>Browser</th>
<th>Platform(s)</th>
<th>Engine version</th>
<th>CSS grade</th>
</tr>
</tfoot>-->
</table>
4.4.4、编写代码
ProductController
@Controller //这个是将这个类交给spring容器进行管理
@RequestMapping("/product") //这个访问的URL 一级路径
public class ProductController {
@Autowired
private IProductService productService;
//查询所有的商品信息 未分页
@RequestMapping("/findAll.do") //这个是二级路径
public ModelAndView findAll() throws Exception{
ModelAndView mv = new ModelAndView(); //这个床架 ModelAndView 对象
List<Product> products = productService.findAll(); //这个是调用service层的所有的方法
mv.addObject("productList",products);//将查询的结果放在 ModelAndView 中
mv.setViewName("product-list"); //这个是要到的那个jsp的界面,要想要生效,前提是你得在springMVC中有过配置
return mv;//将 ModelAndView 返回
}
}
上面基本上可以搭建一个SSM的框架,实现了一个基本查询所有的操作,其他的业务就可以在此基础上实行,创建项目的时候,分模块创建的好处是,可以多个人分工协作,互补干扰,service要是调dao中的代码,只需要一个借口就可以了,互不影响,分工明确,并且配置文件也分散开了,每层互不影响。
下面用来编写一个自定义的字符串变时间的自定义的转换,spring默认的是2018/02/02 这种的格式的,如果你要将字符串时间类型为2018-02-02的格式,则会报错,下面这个可以自定义。
4.5、编写工具类
4.5.1、编写一个字符串日期类型,转换 Date的全局转换
类 DateConverter
/**
* springMVC中自定义类型转换器
* 这个是日期的类型转换器
*
* 实现的步骤是:
* 1. 创建一个类实现实现`Converter`接口
* 2. 实现`convert`方法,方法的参数就是传入的需要转换的数据,方法的返回值就是转换成功之后的数据
* 3. SpringMVC的配置文件中配置自定义转换器
* 4. 修改`<mvc:annotation-driven>`标签让自定义转换器生效
*/
public class DateConverter implements Converter<String,Date>{
/**
* @param source 这个是传入的需要转换的数据,例如:2018-02-02
* @return 返回的数据是转换之后的数据
*/
@Override
public Date convert(String source) {
SimpleDateFormat sdf =null;
if(source!=null){
if(source.contains("-")) {
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}else if(source.contains(".")) {
sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm");
}else if(source.contains("/")){
sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
}
try {
//把字符串转为日期
return sdf.parse(source);
} catch (ParseException e) {
new RuntimeException("数据类型转换失败!");
}
}else {
System.out.println("请传入数据!");
}
return null;
}
}