SSM-CRUD

目标:整合SSM,实现crud功能

查询:

添加

修改

删除

分页

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

要点:

查询:

1.两表联合查询。

2.ajax获取分页数据。

3.拼接HTML语句并显示。

添加:

1.ajax获取部门信息。

2.对员工名以及email的校验

3.员工名是否重复。

修改:

1.员工名为不可修改项。

2.获取对应员工信息并显示。

删除:

1.单个删除 -- 点击当前行后的删除按钮删除。

2.多个删除 -- 勾选复选框,点击记录上方删除按钮删除所选。

3.点击全选框,自动勾选当前页所有记录。

4.当前页记录全部勾选,全选框也会被勾选。

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

具体实现:

数据库方面:

由于只是简单实现crud功能,所以数据库简单设计。

代码编写

 1. 使用mybatis 逆向工程 自动生成相关实体类以及 mapper接口和 mapper.xml

     1.1 配置pom.xml,引入mybatis-generator.jar

	<!-- 逆向工程 -->
		<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
		<dependency>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-core</artifactId>
			<version>1.3.7</version>
		</dependency>

    1.2 引入mgb.xml (逆向工程所必要的xml文件)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>

	<context id="DB2Tables" targetRuntime="MyBatis3">
		<commentGenerator>
			<property name="suppressAllComments" value="true" />
		</commentGenerator>

		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="jdbc:mysql://localhost:3306/db_study?useSSL=false"
			userId="root" password="root">
		</jdbcConnection>

		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>
                // 生成bean对象的位置
		<javaModelGenerator targetPackage="com.yyl.bean"
			targetProject=".\src\main\java">
			<property name="enableSubPackages" value="true" />
			<property name="trimStrings" value="true" />
		</javaModelGenerator>
                // 选择生成的mapper.xml文件位置
		<sqlMapGenerator targetPackage="mapper"
			targetProject=".\src\main\resources">
			<property name="enableSubPackages" value="true" />
		</sqlMapGenerator>
                // 选择生成的mapper接口位置
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="com.yyl.dao" targetProject=".\src\main\java">
			<property name="enableSubPackages" value="true" />
		</javaClientGenerator>
                // 选择生成的bean 来源的表
		<table tableName="tbl_emp" domainObjectName="Employee"></table>
		<table tableName="tbl_dept" domainObjectName="Department"></table>

	</context>

</generatorConfiguration>

   1.3 测试生成

public class MbgTest {

	@Test
	public void testMbg() throws Exception, XMLParserException {
		List<String> warnings = new ArrayList<String>();
		boolean overwrite = true;
                                        // 更改为自己所编写的xml文件名字
		File configFile = new File("mbg.xml");
		ConfigurationParser cp = new ConfigurationParser(warnings);
		Configuration config = cp.parseConfiguration(configFile);
		DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
		myBatisGenerator.generate(null);
	}
}

2.修改相关的mapper.xml文件,是的实现多表联合查询(实现查询did同时查询到相关的deptName)

      因为逆向工程生成的 Employee 没有deptName,所以需要先给Employee添加属性deptName

// 添加 新的 resultMap
<resultMap type="com.yyl.bean.Employee" id="WithDeptMap">
		<id column="emp_id" jdbcType="INTEGER" property="empId" />
		<result column="emp_name" jdbcType="VARCHAR" property="empName" />
		<result column="gender" jdbcType="CHAR" property="gender" />
		<result column="email" jdbcType="VARCHAR" property="email" />
		<result column="d_id" jdbcType="INTEGER" property="dId" />
		<association property="department"
			javaType="com.yyl.bean.Department">
			<id column="dept_id" property="deptId" />
			<result column="dept_name" property="deptName" />
		</association>
	</resultMap>
<!-- 带department的查询 -->
	<select id="selectByExampleWithDept"
		parameterType="com.yyl.bean.EmployeeExample" resultMap="WithDeptMap">
		select
		<if test="distinct">
			distinct
		</if>
		<include refid="WithDept_Column_List" />
		FROM tbl_emp e LEFT JOIN tbl_dept d ON e.d_id = d.dept_id
		<if test="_parameter != null">
			<include refid="Example_Where_Clause" />
		</if>
		<if test="orderByClause != null">
			order by ${orderByClause}
		</if>
	</select>


	<select id="selectByPrimaryKeyWithDept"
		parameterType="java.lang.Integer" resultMap="WithDeptMap">
		select
		<include refid="WithDept_Column_List" />
		FROM tbl_emp e LEFT JOIN tbl_dept d ON e.d_id = d.dept_id
		where emp_id
		= #{empId,jdbcType=INTEGER}
	</select>

3.前端部分 (不包含javascript)

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!-- 获取项目的绝对路径 -->
<%
	pageContext.setAttribute("APP_PATH", request.getContextPath());
%>
<!-- 
		WEB 项目中
		 不以  / 开头的相对路径,找资源以当前资源路径为基准,容易出问题。
		 以 / 开头的绝对路径,找资源以服务器的路径为标准(http://localhost:8080),需要加上项目名。
	
	 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>员工信息</title>
<script type="text/javascript"
	src="${APP_PATH}/static/js/jquery-1.12.4.min.js"></script>
<link
	href="${APP_PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"
	rel="stylesheet">
<script
	src="${APP_PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
	<!-- 员工修改模态框 -->
	<div class="modal fade" id="emp_update_model" tabindex="-1" role="dialog"
		aria-labelledby="myModalLabel">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header ">
					<button type="button" class="close" data-dismiss="modal"
						aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
					<h4 class="modal-title" id="myModalLabel">修改员工信息</h4>
				</div>
				<div class="modal-body">

					<form class="form-horizontal" id="update_Form">
						<div class="form-group">
							<label for="input_empName" class="col-sm-2 control-label">empName</label>
							<div class="col-sm-10" id="update_empName_fa">
								<p class="form-control-static" id="update_empName_static"></p>
								<span class="help-block"></span>
							</div>

						</div>
						<div class="form-group">
							<label for="input_email" class="col-sm-2 control-label">email</label>
							<div class="col-sm-10" id="update_email_fa">
								<input type="text" class="form-control" id="update_input_email"
									name="email" placeholder="xxx@xxx.com"> <span
									class="help-block"></span>
							</div>
						</div>
						<div class="form-group">
							<label for="input_email" class="col-sm-2 control-label">gender</label>
							<div class="col-sm-8">
								<label class="radio-inline"> <input type="radio"
									name="gender" id="sex" value="1" checked="checked"> 男
								</label> <label class="radio-inline"> <input type="radio"
									name="gender" id="sex" value="0"> 女
								</label>
							</div>
						</div>
						<div class="form-group">
							<label for="input_email" class="col-sm-2 control-label">department</label>
							<div class="col-sm-8">
								<select class="form-control" name="dId" id="update_sel">
								</select>
							</div>
						</div>
					</form>

				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
					<button type="button" class="btn btn-primary" id="update_save_Empbtn">修改</button>
				</div>
			</div>
		</div>
	</div>



	<!-- 员工添加模态框 -->
	<div class="modal fade" id="myModal" tabindex="-1" role="dialog"
		aria-labelledby="myModalLabel">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header ">
					<button type="button" class="close" data-dismiss="modal"
						aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
					<h4 class="modal-title" id="myModalLabel">添加员工信息</h4>
				</div>
				<div class="modal-body">

					<form class="form-horizontal" id="save_Form">
						<div class="form-group">
							<label for="input_empName" class="col-sm-2 control-label">empName</label>
							<div class="col-sm-10" id="empName_fa">
								<input type="text" class="form-control" name="empName"
									id="input_empName" id="empName" placeholder="empName">
								<span class="help-block"></span>
							</div>

						</div>
						<div class="form-group">
							<label for="input_email" class="col-sm-2 control-label">email</label>
							<div class="col-sm-10" id="email_fa">
								<input type="text" class="form-control" id="input_email"
									name="email" placeholder="xxx@xxx.com"> <span
									class="help-block"></span>
							</div>
						</div>
						<div class="form-group">
							<label for="input_email" class="col-sm-2 control-label">gender</label>
							<div class="col-sm-8">
								<label class="radio-inline"> <input type="radio"
									name="gender" id="sex" value="1" checked="checked"> 男
								</label> <label class="radio-inline"> <input type="radio"
									name="gender" id="sex" value="0"> 女
								</label>
							</div>
						</div>
						<div class="form-group">
							<label for="input_email" class="col-sm-2 control-label">department</label>
							<div class="col-sm-8">
								<select class="form-control" name="dId" id="sel">
								</select>
							</div>
						</div>
					</form>

				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
					<button type="button" class="btn btn-primary" id="save_Empbtn">保存</button>
				</div>
			</div>
		</div>
	</div>


	<div class="container">
		<!-- 标题 -CRUD 栏-->
		<div class="row">
			<div class="col-md-12">
				<h1>SSM-CRUD</h1>
			</div>
		</div>
		<!-- 操作按钮 栏-->
		<div class="row">
			<div class="col-md-3 col-md-offset-10">
				<button class="btn btn-primary" id="add_model">添加</button>
				<button class="btn btn-danger" id="btn-danger" >删除</button>
			</div>
		</div>
		<!-- 展示数据栏 -->
		<div class="row">
			<div class="col-md-12">
				<table class="table table-hover">
					<thead>
						<tr>
							<th>
								<input type="checkbox" id="check_All" />
							</th>
							<th>#</th>
							<th>Name</th>
							<th>Gender</th>
							<th>Email</th>
							<th>DeptName</th>
							<th>操作</th>
						</tr>
					</thead>
					<tbody id="tbody">
					</tbody>
				</table>
			</div>
		</div>

		<!-- 分页相关栏 -->
		<div class="row">
			<!-- 分页相关记录数 -->
			<div class="col-md-6" id="page_Num_Info"></div>
			<!-- 分页条数 -->
			<div class="col-md-6" id="page_Pages">
				<!-- 分页 -->

			</div>
		</div>
	</div>

3.1 添加模态框的 empName,email 前端校验 以及获取分页数据

<script type="text/javascript">
		// 总页数    
		var totalPage;
		// 当前页
		var currentPage;
		// 校验信息 --信息是否全部正确,如果信息填写不正确 无法提交,保存按钮无法点击。
			// 获取 添加模态框中的,empName对象
		var empName = $("#input_empName");
			// 获取 添加模态框中的, email对象
		var email = $("#input_email");
		
		/* ajax 获取分页相关数据  */
		$(function() {
			to_Page(1);
			getDepts("#sel",0);
			/* 绑定点击添加按钮 弹出模态框事件 */
			$("#add_model").click(function() {
				resetForm("#save_Form");
				$("#myModal").modal({
					backdrop : "static"
				})
			})
			saveEmp();
		})
		
		/* 删除当前行信息 - 删除按钮添加事件 */
		$(document).on("click",".del_btn",function(){
			// 当前行 的 员工名id
			var id = $(this).attr("del_id");
			// 当前行员工名
			var empName=$(this).parents("tr").find("td:eq(1)").text();
			// 确认框
			if(confirm("确认删除  ["+ empName +"] 吗?")){
				// 确认删除发送ajax请求删除
				$.ajax({
					type:"delete",
					url:"${APP_PATH}/emp/"+id,
					success:function(result){
						if(result.code==100){
							to_Page(currentPage);
						}else{
							alert("删除失败!!!");
						}
			
					}
					
				})
			}
		})
		
		
		/* 为修改按钮。绑定事件
			   	--- 无法直接绑定,因为是网页加载完成后,执行事件绑定,但是,修改与删除按钮皆为,页面加载完成后,独立发出的ajax请求,无法绑定
			   	解决: 1. 在创建修改或删除按钮时,绑定事件,缺点:麻烦
			   		2. 使用 jquery on方法,可以绑定。
		*/ 
		$(document).on("click",".edit_btn",function(){
			/* 0.  清除上次显示内容  */
			$("#update_sel").empty();
			// 获取部门信息
			getDepts("#update_sel");
			// 查询员工信息(单个)
				// 获取当前行的员工id
			var id = $(this).attr("edit_id");
				// 获取信息
			getEmp(id);	
				// 给修改按钮加上id值,方便修改操作
			$("#update_save_Empbtn").attr("edit_id",id);
			
			// 弹出修改模态框
			 $("#emp_update_model").modal({
					backdrop : "static"
				}) 
				
		})
		// 根据id 获取员工信息
		function getEmp(id){
			$.get("${APP_PATH}/emp/"+id,{},function(result){
				var emp = result.extend.employee;
				// 设置empName - <p>
				$("#update_empName_static").text(emp.empName);
				// 设置email -input
				$("#update_input_email").val(emp.email);
				// 设置gender -radio
				$("#emp_update_model input[name=gender]").val([emp.gender]);
				// 设置部门
				$("#update_sel").val([emp.dId]);
			})	
		}
		
		/* 当点击全选框,自动选中所有的 */
		$("#check_All").click(function(){
		
			$(".check_item").prop("checked",$(this).prop("checked"))
			
		})
		/* 当某一页的单选框全部被点击时,全选框也会被选  */
		$(document).on("click",".check_item",function(){
			
			if($(".check_item:checked").length==$(".check_item").length){
				$("#check_All").prop("checked","checked");
			}else{
				$("#check_All").prop("checked",false);
			}
			
		})
		
		$("#btn-danger").click(function(){
			var empNames=" ";
			var empIds="";
			// 将选中的复选框的 name 拼接字符串,显示在提示框
			$.each($(".check_item:checked"),function(){
				var empName = $(this).parents("tr").find("td:eq(2)").text();
				empNames=empNames+empName+",";
			})
			empNames=empNames.substring(0,empNames.length-1)
			if(confirm("你确认要删除"+empNames+"吗")){
				// 将选中的复选框的id拼接 为 x-x-x形式,
				$.each($(".check_item:checked"),function(){
					var empId = $(this).parents("tr").find("td:eq(1)").text();
					empIds=empIds+empId+"-";
				})
				// 去除最后一个 - 
				empIds = empIds.substring(0,empIds.length-1);
				// 发送ajax请求,执行删除操作
				
				$.ajax({
					type:"delete",
					url:"${APP_PATH}/emp/"+empIds,
					success:function(result){
						to_Page(currentPage);
					}
				})
				
			}
			
		})
		
		
		/* 为修改保存按钮添加事件 */
		$("#update_save_Empbtn").click(function(){
			
			/* 1 . 校验邮箱格式 */
			var emailRex = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
			if (emailRex.test($("#update_input_email").val())) {
				showMsg("#update_input_email", true, "");
			} else {
				showMsg("#update_input_email", false, "邮箱格式错误,请更正,例如:admin@qq.com");
				return false;
			}
			
				//取出当前修改的id
			var id=$("#update_save_Empbtn").attr("edit_id");
			/*2.发送ajax请求,完成修改  */
			$.ajax({
			type:"put",
			url:"${APP_PATH}/emp/"+id,
			data:$("#update_Form").serialize(),
			success:function(result){
				// 修改成功后,关闭模态框,并跳转到当前页
				$("#emp_update_model").modal("hide");
				to_Page(currentPage);
			}
			})
			
		})
		
		/* 清除上一次校验留下的类以及提示信息 */
		function resetForm(ele) {
			$(ele)[0].reset();
			$(ele).find("*").removeClass("has-success has-error");
			$(ele).find(".help-block").text("");
		}
		/* 
		var empName = $("#input_empName");
		var email = $("#input_email");
		 */
		// 校验 用户名 和 email 格式
		function validate() {
			var empNameRex = /\w{6,12}/;
			var emailRex = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
			// 校验 用户名
			if (empNameRex.test(empName.val())) {
				showMsg("#input_empName", true, "");
			} else {
				showMsg("#input_empName", false,
						"用户名必须为6 - 12 为英文字符 或 3-6位中文字符");
				return false;
			}
			// 校验邮箱格式
			if (emailRex.test(email.val())) {
				showMsg("#input_email", true, "");
			} else {
				showMsg("#input_email", false, "邮箱格式错误,请更正,例如:admin@qq.com");
				return false;
			}
			return true;
		}
		 /* 接收参数:ele 元素,flag:校验正确与否,msg:提示信息
		 		-- 在校验后,显示相关提示信息。
		 */
		function showMsg(ele, flag, msg) {
			// 在显示其他消息前,需要清除该元素之前的操作
			$(ele).parent().removeClass("has-error has-success");
			$(ele).next("span").text("");
			if (flag == true) {
				$(ele).parent().addClass("has-success");
				$(ele).next("span").text("");
			} else {
				$(ele).parent().addClass("has-error");
				$(ele).next("span").text(msg);
			}
		}
		
		 /* 当员工名改变时发送ajax请求,判断该名是否重复 */
		$("#input_empName").change(function() {
			var empName = this.value;
			$.post("${APP_PATH}/checkname", {
				empName : empName
			}, function(result) {
				if (result.code == 100) {
					showMsg("#input_empName", true, "用户名可用");
					$("#save_Empbtn").attr("ajax-va", true)
				} else {
					showMsg("#input_empName", false, "用户名已存在");
					$("#save_Empbtn").attr("ajax-va", false)
				}
			})
		})

		// 保存员工信息
		function saveEmp() {
			$("#save_Empbtn")
					.click(
							function() {
								/* 	if (!validate()) {
										return false;
									} */
								if ($("#save_Empbtn").attr("ajax-va") == false) {
									alert("1111")
									return false;
								}
								$
										.post(
												"${APP_PATH}/emp",
												$("#save_Form").serialize(),
												function(result) {
													if (result.code == 100) {
														$("#myModal").modal(
																"hide");
														to_Page(totalPage);
													} else {
														if (undefined != result.extend.errors.empName) {
															showMsg(
																	"#input_empName",
																	false,
																	result.extend.errors.empName);
														}
														if (undefined != result.extend.errors.email) {
															showMsg(
																	"#input_email",
																	false,
																	result.extend.errors.email);
														}
													}
												})
							})
		}

		/* 获取部门信息  */
		function getDepts(ele,did) {
			$.get("${APP_PATH}/depts", {}, function(data) {
				var depts = data.extend.depts;
				var sel = $(ele);
				$.each(depts, function(index, dept) {
					var opt = $("<option></option>").append(dept.deptName)
							.attr("value", dept.deptId);
					if(did==dept.deptId){
						 opt = $("<option></option>").append(dept.deptName)
						.attr("value", dept.deptId).prop("selected","selected");
					}
					sel.append(opt);
				})
			})
		}

		/* 显示分页条  -- 从哪一页(pn)开始 */
		function to_Page(pn) {
			$.get("${APP_PATH}/emps", {
				pn : pn
			}, function(data) {
				showEmps(data);
				showPageNums(data);
				showPages(data);
			})
		}

		/* 显示员工信息 */
		function showEmps(data) {
			// 清空之前的信息 ,不清空会累积在一起
			$("#tbody").empty();

			/* 获取所有员工信息 */
			var emps = data.extend.pageInfo.list;
			$.each(emps, function(index, emp) {
				var checkbox = $("<td></td>").append("<input type='checkbox' class='check_item'/>");
				var empId = $("<td></td>").append(emp.empId);
				var empName = $("<td></td>").append(emp.empName);
				var gender = $("<td></td>").append(
						emp.gender == "1" ? "男" : "女");
				var email = $("<td></td>").append(emp.email);
				var deptName = $("<td></td>").append(emp.department.deptName);

				var editbtn = $("<button></button>").addClass(
						"btn btn-info btn-sm edit_btn").append(
						$("<span></span>").addClass(
								"glyphicon glyphicon-pencil ")).append("修改");
				editbtn.attr("edit_id",emp.empId);
				var delbtn = $("<button></button>").addClass(
						"btn btn-danger btn-sm del_btn").append(
						$("<span></span>")
								.addClass("glyphicon glyphicon-trash")).append(
						"删除");
				delbtn.attr("del_id",emp.empId);
				var btn = $("<td></td>").append(editbtn).append(" ").append(
						delbtn);
				$("<tr></tr>").append(checkbox).append(empId).append(empName).append(gender)
						.append(email).append(deptName).append(btn).appendTo(
								"#tbody");
			})

		}

		/* 显示分页条目信息 */
		function showPageNums(data) {
			$("#page_Pages").empty();
			var pageInfo = data.extend.pageInfo;
			currentPage = pageInfo.pageNum;
			totalPage = pageInfo.total;
			$("#page_Num_Info").html(
					"当前第" + pageInfo.pageNum + "页 , 总" + pageInfo.pages + "页,总"
							+ pageInfo.total + "条记录数")
		}

		/* 显示分页条信息 */
		function showPages(data) {
			$("#page_Pages").empty();
			var pageInfo = data.extend.pageInfo;
			var ul = $("<ul></ul>").addClass("pagination");
			var firstPage = $("<li></li>").append($("<a></a>").append("首页"));
			var prePage = $("<li></li>").append($("<a></a>").append("&laquo;"));
			var nextPage = $("<li></li>")
					.append($("<a></a>").append("&raquo;"));
			var lastPage = $("<li></li>").append($("<a></a>").append("尾页"));
			/* 为分页加点击事件 */
			/* 如果处于第一页,那么首页 与 前一页 处于禁止点击状态  */
			if (pageInfo.hasPreviousPage == false) {
				prePage.addClass("disabled");
				firstPage.addClass("disabled");
			} else { /* 点击前一页  */
				firstPage.click(function() {
					to_Page(1);
				});
				prePage.click(function() {
					to_Page(pageInfo.pageNum - 1);
				});
			}
			/* 如果处于最后一页,那么尾页 以及 后一页 处于禁止点击状态  */
			if (pageInfo.hasNextPage == false) {
				nextPage.addClass("disabled");
				lastPage.addClass("disabled");
			} else {
				lastPage.click(function() {
					to_Page(pageInfo.pages);
				});
				/* 点击后一页  */
				nextPage.click(function() {
					to_Page(pageInfo.pageNum + 1);
				});
			}

			var nums = data.extend.pageInfo.navigatepageNums;
			ul.append(firstPage);
			ul.append(prePage);
			$.each(nums, function(index, num) {
				var li = $("<li></li>").append($("<a></a>").append(num));
				if (num == data.extend.pageInfo.pageNum) {
					li.addClass("active");
				}
				li.click(function() {
					to_Page(num);
				})
				ul.append(li);
			})
			ul.append(nextPage);
			ul.append(lastPage);
			var nav = $("<nav></nav>").append(ul);
			$("#page_Pages").html(nav);
		}
	</script>

4.controller实现

@Controller
public class EmployeeController {

	@Autowired
	EmployeeService employeeService;

	/**
	 * 删:删除员工信息,通过id
	 *  改造之前 -- public Msg deleteById(@PathVariable("id") Integer id) 
	 *  			-- 只能执行单一删除
	 *  改造之后 -- public Msg deleteById(@PathVariable("ids") String ids)
	 *  			-- 可以执行单一 以及多个删除
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/emp/{ids}", method = RequestMethod.DELETE)
	@ResponseBody
	public Msg deleteById(@PathVariable("ids") String ids) {
		String[] split = ids.split("-");


		if(split.length==1) {
			employeeService.deleteEmp(Integer.parseInt(split[0]));
		}else {
			employeeService.deleteEmps(split);
		}
		return Msg.success();
	}

	/**
	 * 改: 保存修改
	 * 
	 * @param emp
	 * @return
	 */
	@RequestMapping(value = "/emp/{empId}", method = RequestMethod.PUT)
	@ResponseBody
	public Msg saveUpdate(Employee emp) {
		System.out.println(emp);
		long i = employeeService.saveUpdate(emp);
		if (i > 0)
			return Msg.success();
		else
			return Msg.fail();
	}

	/**
	 * 查: 修改员工信息,先获取员工信息,显示
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/emp/{id}", method = RequestMethod.GET)
	@ResponseBody
	public Msg getEmp(@PathVariable("id") Integer id) {
		Employee emp = employeeService.getEmp(id);
		return Msg.success().add("employee", emp);
	}

	/**
	 * 检查添加员工时姓名是否重复
	 * 
	 * @param empName
	 * @return
	 */
	@RequestMapping("/checkname")
	@ResponseBody
	public Msg checkName(@RequestParam("empName") String empName) {
		boolean flag = employeeService.checkName(empName);
		System.out.println(flag);
		if (flag) {
			return Msg.success();
		} else {
			return Msg.fail();
		}
	}

	/**
	 * 增: 保存员工信息
	 * 
	 * @param employee
	 * @param result
	 * @return
	 */
	@RequestMapping(value = "/emp", method = RequestMethod.POST)
	@ResponseBody
	public Msg saveEmp(@Valid Employee employee, BindingResult result) {
		if (result.hasErrors()) {
			Map<String, Object> map = new HashMap<>();
			List<FieldError> fieldErrors = result.getFieldErrors();
			for (FieldError fieldError : fieldErrors) {
				System.out.println("错误字段名:" + fieldError.getField());
				System.out.println("错误信息:" + fieldError.getDefaultMessage());
				map.put(fieldError.getField(), fieldError.getDefaultMessage());
			}
			System.out.println("has error");
			return Msg.fail().add("errors", map);
		} else {
			System.out.println(employee);
			int i = employeeService.saveEmp(employee);
			if (i > 0) {
				return Msg.success();
			} else {
				System.out.println("i am has error");
				return Msg.fail();
			}
		}
	}

	/**
	 * 查 :获取所有员工信息 - 显示在主页面 - ajax方式请求
	 * 
	 * @param pn
	 * @param model
	 * @return
	 */
	@RequestMapping("/emps")
	@ResponseBody
	public Msg getEmpsWithJson(@RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model) {

		PageHelper.startPage(pn, 5);
		List<Employee> emps = employeeService.getAllEmps();
		PageInfo pageInfo = new PageInfo(emps, 5);

		return Msg.success().add("pageInfo", pageInfo);
	}

	/**
	 * 获取所有员工信息 显示在主页面 - 通过el表达式显示在主页面
	 * 
	 * @param pn
	 * @param model
	 * @return
	 */
	// @RequestMapping("/emps")
	public String getEmployees(@RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model) {

		PageHelper.startPage(pn, 5);
		List<Employee> emps = employeeService.getAllEmps();
		PageInfo pageInfo = new PageInfo(emps, 5);
		model.addAttribute("pageInfo", pageInfo);
		List<Employee> list = pageInfo.getList();
		for (Employee employee : list) {
			System.out.println(employee.toString());
		}
		return "list";
	}

}

5.相关ssm配置

// spring-servlet.xml 放于WEB-INF下
<?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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		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-4.3.xsd">
	<!-- 只扫描控制器,springmvc.xml只负责控制网站逻辑跳转 -->
	<context:component-scan base-package="com.yyl"
		use-default-filters="false">
		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
	<!-- 视图解析器 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	<!-- 两个重要标准配置 必须配置 -->
	<!-- 解决静态资源访问问题 -->
	<mvc:default-servlet-handler />
	<!-- 解决jsr303 等springmvc高级功能问题 -->
	<mvc:annotation-driven />

</beans>
// mybatis.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">
<configuration>
	<!-- 自动驼峰命名转换 eg: user_name userName -->
	<settings>
		<setting name="mapUnderscoreToCamelCase" value="true" />
	</settings>
	<!-- 别名  eg: 类: Employee 别名:employee -->
	<typeAliases>
		<package name="com.yyl.bean" />
	</typeAliases>
	<!-- 分页插件 -->
	<plugins>
		<!-- com.github.pagehelper为PageHelper类所在包名 -->
		<plugin interceptor="com.github.pagehelper.PageInterceptor">
			<property name="reasonable" value="true"/>
		</plugin>
	</plugins>
</configuration>
// spring配置文件 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:tx="http://www.springframework.org/schema/tx"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		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-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

	<!-- Spring (数据源、与mybatis的整合、事务控制) 负责管理所有的业务逻辑组件 -->


	<!-- ===============================1.spring(IOC)相关配置======================================== -->
	<!-- 加载属性配置文件 -->
	<context:property-placeholder
		location="classpath:dbconfig.properties" />
	<!-- spring 扫描除了 标注 controller以外的所有 -->
	<context:component-scan base-package="com.yyl">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
	<!-- ================================================================================ -->


	<!-- ===============================2.连接数据源======================================== -->

	<!-- 配置数据源 C3p0 -->
	<bean id="dataSource"
		class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="jdbcUrl" value="${jdbc.url}"></property>
		<property name="driverClass" value="${jdbc.driver}"></property>
		<property name="user" value="${jdbc.user}"></property>
		<property name="password" value="${jdbc.password}"></property>
	</bean>
	<!-- ================================================================================== -->

	<!-- ===============================3.整合mybatis======================================== -->
	<!-- spring-整合mybatis 配置sqlSessionFactory -->
	<bean id="sqlSessionFactory"
		class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 连接的数据源 -->
		<property name="dataSource" ref="dataSource"></property>
		<!-- 指定mybatis的全局配置文件 -->
		<property name="configLocation" value="classpath:mybatis.xml"></property>
		<!-- 指定mapper文件存放位置 - 如果mapper文件与接口存放位置相同 可以不配置 -->
		<property name="mapperLocations"
			value="classpath:mapper/*.xml"></property>
	</bean>

	<!-- 配置扫描器,将mybatis接口的实现加入IOC容器中 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.yyl.dao"></property>
	</bean>
	<!-- ==================================================================================== -->

	<!-- 配置批量插入的sqlSession  :注意 在使用批量插入时,返回值 -2147482646,有问题,正常执行插入,可以注释掉  -->
<!-- 	<bean id="sqlSession"
		class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg name="sqlSessionFactory"
			ref="sqlSessionFactory"></constructor-arg>
		<constructor-arg name="executorType" value="BATCH"></constructor-arg>
	</bean> -->

	<!-- ===============================4.spring事务控制======================================================== -->
	<!-- 事务控制配置 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 事务控制的数据源 -->
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!-- 事务开启,1.基于注解的事务 2.基于配置文件的事务(主要得一般都用2) -->
	<!--1. <mvc:annotation-driven /> -->
	<!--2. -->
	<aop:config>
		<!-- 配置切入点 -->
		<aop:pointcut
			expression="execution(* com.yyl.service..*(..))" id="txPoint" />
		<!-- 事务增强 -->
		<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint" />
	</aop:config>
	<!-- 配置事务增强 事务如何切入 -->
	<tx:advice id="txAdvice">
		<tx:attributes>
			<!-- 所有方法都有事务 -->
			<tx:method name="*" />
			<!-- 以get开头的方法是select查询语句,设置read-only提供性能 -->
			<tx:method name="get*" read-only="true" />
		</tx:attributes>
	</tx:advice>
	<!-- ==================================================================================== -->

</beans>
// web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5"
	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_2_5.xsd">
	<!-- 1.初始化spring容器 -->
	<!-- needed for ContextLoaderListener -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<!-- Bootstraps the root web application context before servlet initialization -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- 2.前端控制器 DispatcherServlet -->
	<!-- The front controller of this Spring Web application, responsible for 
		handling all application requests -->
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<!-- Map all requests to the DispatcherServlet for handling -->
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<!-- 3.字符编码过滤器 -->
	<filter>
		<filter-name>CharacterEncodingFilter</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>forceRequestEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
		<init-param>
			<param-name>forceResponseEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- 4.rest风格 uri 将普通的post请求转换为 delete put请求 -->
	<filter>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<!-- 自动转化请求为 put / delete ,不需要配置 _method参数 -->
	<filter>
		<filter-name>ContentFilter</filter-name>
		<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>ContentFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值