配合哔哩哔哩視訊學習【SSM 架構】SpringMVC+Spring+Mybatis SSM 整合+實戰+源碼19-33集
終章
CRM開發環境搭建
基于前面第七個項目的SSM架構+jquery-easyui 前端UI架構
1.客戶清單展示
1.1.Mapper接口(dao層)
接口:
package com.ssm.dao;
import java.util.List;
import com.ssm.domain.Customer;
public interface CustomerMapper {
/**
* 查詢所有資料
*/
public List<Customer> findAll();
}
sql映射配置
<?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">
<!-- 該檔案編寫mybatis中的mapper接口裡面的方法提供對應的sql語句 -->
<mapper namespace="com.ssm.dao.CustomerMapper">
<!-- 查詢所有資料 -->
<select id="findAll" resultType="com.ssm.domain.Customer">
select id,
NAME,
gender,
telephone,
address
from
ssm.t_customer
</select>
</mapper>
1.2.Service(service層)對Mapper接口進行對接
package com.ssm.service;
import java.util.List;
import com.ssm.domain.Customer;
public interface CustomerService {
/**
* 查詢所有資料
*/
public List<Customer> findAll();
}
實作類:
package com.ssm.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ssm.dao.CustomerMapper;
import com.ssm.domain.Customer;
import com.ssm.service.CustomerService;
@Service("customerServiceImpl")
@Transactional
public class CustomerServiceImpl implements CustomerService {
//注入Mapper接口對象
@Resource
private CustomerMapper customerMapper;
public List<Customer> findAll() {
return customerMapper.findAll();
}
}
1.3.Controller(controller層)
package com.ssm.controller;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ssm.domain.Customer;
import com.ssm.service.CustomerService;
@Controller
@RequestMapping("/customer")
public class CustomerController {
//注入service對象
private CustomerService customerService;
/**
* 查詢所有資料,給頁面傳回Json資料
* easyui的datagrid元件,需要展示資料提供json資料 [{id:1,name:xxx},{id:2,name:xxx}]
*/
@RequestMapping("/list")
@ResponseBody // 用于傳回資料
public List<Customer> list(){
//查詢資料
List<Customer> list = customerService.findAll();
return list;
}
}
這時我們運作項目測試,發現錯誤
報錯顯示,包的版本不相容
原因:springmvc轉換java對象為json資料的時候,jackson插件的版本于springMVC的版本不相容,這裡是它的版本過低,導緻轉換失敗
解決辦法:
更新jackson插件的版本,最好更新到2.6以上
效果:
1.4.頁面
導入easyui的檔案
<!-- 導入easyui的資源檔案 -->
<script type="text/javascript" src="easyui/jquery.min.js"></script>
<script type="text/javascript" src="easyui/jquery.easyui.min.js"></script>
<script type="text/javascript" src="easyui/locale/easyui-lang-zh_CN.js"></script>
<link rel="stylesheet" type="text/css" href="easyui/themes/icon.css">
<link id="themeLink" rel="stylesheet" type="text/css" href="easyui/themes/default/easyui.css">
<table id="list"></table>
<script type="text/javascript">
$(function(){
$("#list").datagrid({
//url:背景資料查詢的位址
url:"customer/listByPage.action",
//columns:填充的列資料
//field:背景對象的屬性
//tille:列标題
columns:[[
{
field:"id",
title:"客戶編号",
width:100,
checkbox:true
},
{
field:"name",
title:"客戶姓名",
width:200
},
{
field:"gender",
title:"客戶性别",
width:200
},
{
field:"telephone",
title:"客戶手機",
width:200
},
{
field:"address",
title:"客戶住址",
width:200
}
]]
});
});
2.客戶分頁顯示
2.1.頁面
$(function(){
$("#listByPage").datagrid({
//url:背景資料查詢的位址
url:"customer/list.action",
//columns:填充的列資料
//field:背景對象的屬性
//tille:列标題
columns:[[
{
field:"id",
title:"客戶編号",
width:100,
checkbox:true
},
{
field:"name",
title:"客戶姓名",
width:200
},
{
field:"gender",
title:"客戶性别",
width:200
},
{
field:"telephone",
title:"客戶手機",
width:200
},
{
field:"address",
title:"客戶住址",
width:200
}
]],
//顯示分頁
pagination:true,
});
});
2.2.Controller
2.2.1.使用mybatis分頁插件
2.2.1.1.導入mybatis分頁插件的jar包
2.2.1.2.配置applicationContext.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">
<!-- 讀取jdbc.properties -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 建立DataSource -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="driverClassName" value="${jdbc.driverClass}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="10"/>
<property name="maxIdle" value="5"/>
</bean>
<!-- 建立SqlSessionFactory對象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 關聯連接配接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 加載sql映射檔案 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
<!-- 引入插件 -->
<property name="plugins">
<array>
<!-- mybatis分頁插件 -->
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<value>
<!--
helperDialect:連接配接資料庫的類型
-->
helperDialect=mysql
</value>
</property>
</bean>
</array>
</property>
</bean>
<!-- 配置Mapper接口掃描 -->
<!--
注意:如果使用Mapper接口包掃描,那麼每個maopper接口在spring容器中的id名稱為類名:例如CustomerMapper->customerMapper
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置mapper接口所在包的路徑 -->
<property name="basePackage" value="com.ssmlcx.dao"/>
</bean>
<!-- 開啟spring的IOC注解掃描 -->
<context:component-scan base-package="com.ssmlcx"></context:component-scan>
<!-- 開啟spring的事務管理 -->
<!-- 事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 啟用spring事務注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
package com.ssm.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.domain.Customer;
import com.ssm.service.CustomerService;
@Controller
@RequestMapping("/customer")
public class CustomerController {
//注入service對象
@Resource
private CustomerService customerService;
/**
* 查詢所有資料,給頁面傳回Json資料
* easyui的datagrid元件,需要展示資料提供json資料 [{id:1,name:xxx},{id:2,name:xxx}]
*/
@RequestMapping("/list")
@ResponseBody // 用于傳回資料
public List<Customer> list(){
//查詢資料
List<Customer> list = customerService.findAll();
return list;
}
//設計Map集合存儲頁面所需要的資料
private Map<String , Object> result = new HashMap<String, Object>();
/**
* 分頁查詢
*/
@RequestMapping("/listByPage")
@ResponseBody
public Map<String, Object> listByPage(Integer page,Integer rows){
//設定分頁的參數
PageHelper.startPage(page,rows);
//查詢所有資料
List<Customer> list = customerService.findAll();
//使用pageInfo封裝查詢結果
PageInfo<Customer> pageInfo = new PageInfo<Customer>();
//從pageInfo對象取出結果
//總記錄數
long total = pageInfo.getTotal();
//目前頁資料清單
List<Customer> customers = pageInfo.getList();
result.put("total", total);
result.put("rows", customers);
return result;
}
}
3.客戶添加
3.1.頁面
增加一個按鈕的工具條
<!-- 工具條 -->
<div id="tb">
<a id="addBtn" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true">添加</a>
<a id="editBtn" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-edit',plain:true">修改</a>
<a id="deleteBtn" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-remove',plain:true">删除</a>
</div>
點選添加按鈕彈出編輯菜單
//打開編輯視窗
$("#addBtn").click(function(){
//清空表單資料
$("#editForm").form("clear");
$("#win").window("open");
});
編輯視窗
<!-- 編輯視窗 -->
<div id="win" class="easyui-window" title="客戶資料編輯" style="width:500px;height:300px"
data-options="iconCls:'icon-save',modal:true,closed:true">
<form id="editForm" method="post">
<%--提供id隐藏域 --%>
<input type="hidden" name="id">
客戶姓名:<input type="text" name="name" class="easyui-validatebox" data-options="required:true"/><br/>
客戶性别:
<input type="radio" name="gender" value="男"/>男
<input type="radio" name="gender" value="女"/>女
<br/>
客戶手機:<input type="text" name="telephone" class="easyui-validatebox" data-options="required:true"/><br/>
客戶住址:<input type="text" name="address" class="easyui-validatebox" data-options="required:true"/><br/>
<a id="saveBtn" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-save'">儲存</a>
</form>
</div>
将前台的資料傳遞到背景
//儲存資料
$("#saveBtn").click(function(){
$("#editForm").form("submit",{
//url: 送出到背景的位址
url:"customer/save.action",
//onSubmit: 表單送出前的回調函數,true:送出表單 false:不送出表單
onSubmit:function(){
//判斷表單的驗證是否都通過了
return $("#editForm").form("validate");
},
//success:伺服器執行完畢回調函數
success:function(data){ //data: 伺服器傳回的資料,類型字元串類
//要求Controller傳回的資料格式:
//成功:{success:true} 失敗:{success:false,msg:錯誤資訊}
//把data字元串類型轉換對象類型
data = eval("("+data+")");
if(data.success){
//關閉視窗
$("#win").window("close");
//重新整理datagrid
$("#list").datagrid("reload");
$.messager.alert("提示","儲存成功","info");
}else{
$.messager.alert("提示","儲存失敗:"+data.msg,"error");
}
}
});
});
3.2.Controller
/**
* 儲存資料
*/
@RequestMapping("/save")
@ResponseBody
public Map<String , Object> save(Customer customer)
{
try {
customerService.save(customer);
result.put("success", true);
} catch (Exception e) {
e.printStackTrace();
result.put("success", false);
result.put("msg", e.getMessage());
}
return result;
}
3.3.Service
接口:
package com.ssm.service;
import java.util.List;
import com.ssm.domain.Customer;
public interface CustomerService {
/**
* 查詢所有資料
*/
public List<Customer> findAll();
public void save(Customer customer);
}
實作:
package com.ssm.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ssm.dao.CustomerMapper;
import com.ssm.domain.Customer;
import com.ssm.service.CustomerService;
@Service("customerServiceImpl")
@Transactional
public class CustomerServiceImpl implements CustomerService {
//注入Mapper接口對象
@Resource
private CustomerMapper customerMapper;
public List<Customer> findAll() {
return customerMapper.findAll();
}
public void save(Customer customer) {
customerMapper.save(customer);
}
}
3.4.Mapper
/**
* 儲存資料
* @param customer
*/
public void save(Customer customer);
3.5.sql映射檔案
<!-- 增加資料 -->
<insert id="save" parameterType="com.ssm.domain.Customer">
insert into ssm.t_customer(
NAME,
gender,
telephone,
address
)
values(
#{name},
#{gender},
#{telephone},
#{address}
)
</insert>
4.客戶資訊修改回顯
4.1.頁面
//修改資料
$("#editBtn").click(function(){
//判斷隻能選擇一行
var rows = $("#list").datagrid("getSelections");
if(rows.length!=1){
$.messager.alert("提示","修改操作隻能選擇一行","warning");
return;
}
//表單回顯
$("#editForm").form("load","customer/findById.action?id="+rows[0].id);
$("#win").window("open");
});
4.2.Controller
/**
* 根據id 查詢對象
*/
@RequestMapping("/findById")
@ResponseBody
public Customer findById(Integer id)
{
Customer customer = customerService.findById(id);
return customer;
}
4.3.Service
接口:
實作:
public Customer findById(Integer id) {
return customerMapper.findById(id);
}
4.4.Mapper
/**
* 根據id 查詢對象
* @param id
* @return
*/
public Customer findById(Integer id);
4.5.sql映射檔案
<!-- 根據id查詢對象 -->
<select id="findById" parameterType="int" resultType="com.ssm.domain.Customer">
select id,
NAME,
gender,
telephone,
address
from
ssm.t_customer where
id = #{value}
</select>
5.客戶資訊更新儲存
5.1.頁面
//修改資料
$("#editBtn").click(function(){
//判斷隻能選擇一行
var rows = $("#list").datagrid("getSelections");
if(rows.length!=1){
$.messager.alert("提示","修改操作隻能選擇一行","warning");
return;
}
//表單回顯
$("#editForm").form("load","customer/findById.action?id="+rows[0].id);
$("#win").window("open");
});
5.2.Controller
/**
* 儲存資料
*/
@RequestMapping("/save")
@ResponseBody
public Map<String , Object> save(Customer customer)
{
try {
customerService.save(customer);
result.put("success", true);
} catch (Exception e) {
e.printStackTrace();
result.put("success", false);
result.put("msg", e.getMessage());
}
return result;
}
5.3.Service
接口:
實作:
public void save(Customer customer) {
//判斷是修改還是增加
if (customer.getId() != null) {
//修改
customerMapper.update(customer);
} else {
//增加
customerMapper.save(customer);
}
}
5.4.Mapper
/**
* 修改對象資料
* @param customer
*/
public void update(Customer customer);
5.5.sql映射檔案
<!-- 根據id修改對象資料 -->
<update id="update" parameterType="com.ssm.domain.Customer">
update ssm.t_customer
set
NAME = #{name},
gender = #{gender},
telephone = #{telephone},
address = #{address}
where
id=#{id}
</update>
6.客戶資訊删除
6.1.頁面
//删除
$("#deleteBtn").click(function(){
var rows =$("#list").datagrid("getSelections");
if(rows.length==0){
$.messager.alert("提示","删除操作至少選擇一行","warning");
return;
}
//格式: id=1&id=2&id=3
$.messager.confirm("提示","确認删除資料嗎?",function(value){
if(value){
var idStr = "";
//周遊資料
$(rows).each(function(i){
idStr+=("id="+rows[i].id+"&");
});
idStr = idStr.substring(0,idStr.length-1);
//傳遞到背景
$.post("customer/delete.action",idStr,function(data){
if(data.success){
//重新整理datagrid
$("#list").datagrid("reload");
$.messager.alert("提示","删除成功","info");
}else{
$.messager.alert("提示","删除失敗:"+data.msg,"error");
}
},"json");
}
});
});
6.2.Controller
/**
* 删除資料
*/
@RequestMapping("delete")
@ResponseBody
public Map<String, Object> delete(Integer[] id){
try {
customerService.delete(id);
result.put("success", true);
} catch (Exception e) {
e.printStackTrace();
result.put("success", false);
result.put("msg", e.getMessage());
}
return result;
}
6.3.Service
6.4.Mapper
/**
* 删除資料
* @param id
*/
public void delete(Integer[] id);
6.5.sql映射檔案
<!-- 删除 -->
<delete id="delete" parameterType="Integer[]">
delete from ssm.t_customer
<where>
id
<foreach collection="array" item="id" open="in (" close=")" separator=",">
#{id}
</foreach>
</where>
</delete>