基于SSM框架的web入门项目(八)终章·学习记录

配合哔哩哔哩视频学习【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);

实现:

	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);

实现:

	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

	public void delete(Integer[] id);	

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>
发布了56 篇原创文章 · 获赞 70 · 访问量 8905

猜你喜欢

转载自blog.csdn.net/weixin_44835732/article/details/103833535