SSM项目开发
基本配置
引入前端框架Bootstrap
在需要的jsp页面中引入Bootstrap:
<!-- 引入 Bootstrap -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
web.xml基本配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--1 配置Spring的容器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--2 配置springMvc拦截器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</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风格的URL的过滤器-->
<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>
<!--处理tomcat不能处理pot请求的过滤器-->
<filter>
<filter-name>HttpPutFormContentFilter</filter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HttpPutFormContentFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
applicationContext.xml配置(Spring文件配置)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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.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
">
<!--Spring配置文件-->
<!--开启注解扫描-->
<context:component-scan base-package="com.xzh">
<!--过滤掉Controller注解-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--引入配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="password" value="${jdbc.password}"/>
<property name="username" value="${jdbc.username}"/>
<property name="url" value="${jdbc.url}"/>
</bean>
<!--配置MyBatis整合=====================-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--指定mybatis全局配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--配置数据源-->
<property name="dataSource" ref="dataSource"/>
<!--指定mapper文件-->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!--配置扫描器 将mybatis加载到容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描所有的dao接口的实现 -->
<property name="basePackage" value="com.xzh.dao"/>
</bean>
<!--配置一个可以执行批量的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" >
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
<constructor-arg name="executorType" value="BATCH"/>
</bean>
<!--配置MyBatis整合=====================-->
<!--事物控制-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--控制数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--开启事务-->
<aop:config>
<!--切入点表达式-->
<aop:pointcut id="txPoint" expression="execution(* com.xzh.service..*(..))"/>
<!--事务增强-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
</aop:config>
<!--配置事务增强,事物如何切入-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--所有方法都是事务方法-->
<tx:method name="*"/>
<!--以get开始的方法-->
<tx:method name="get*" read-only="true"/>
</tx:attributes>
</tx:advice>
</beans>
spring-mvc文件配置
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns="http://www.springframework.org/schema/beans"
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
">
<!--SpringMvc配置 包含网站跳转配置-->
<context:component-scan base-package="com.xzh" use-default-filters="false">
<!--只扫描控制器注解-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--配置视图解析器,方便返回-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--两个标准配置-->
<!--找不到的资源让tomcat去找-->
<mvc:default-servlet-handler/>
<!--更高级的一些操作 注解加载-->
<mvc:annotation-driven/>
</beans>
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">
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="com.xzh.bean"/>
</typeAliases>
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql"/>
<!--分页合理化 让分页不能转到不正确的地方-->
<property name="reasonable" value="true"/>
</plugin>
</plugins>
</configuration>
使用mybatis逆向自动生成doman、dao、mapper
在pom.xml中导入包
<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
在项目根目录下创建mbg.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">
<!--让他生成的doman没有注释-->
<commentGenerator>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--配置数据库的连接信息-->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql:///ssm_crud"
userId="root"
password="000000">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!--指定javaBean生成的位置-->
<javaModelGenerator targetPackage="com.xzh.bean" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!--指定sql映射文件生成的位置-->
<sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!--指定dao接口生成的位置 mapper-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.xzh.dao" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!--制定每个表格的生成策略--> <!--tableName是表名 domainObjectName是生成的java类名-->
<table tableName="tbl_emp" domainObjectName="Employee"/>
<table tableName="tnl_dept" domainObjectName="Department"/>
</context>
</generatorConfiguration>
直接执行代码:
public static void main(String[] args) throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
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);
}
生成后的文件:
在最后修改一下其中的sql逻辑即可
注意***************************
需要注意的是Mybatis用这种逆向方法 好像会自动把接口放入ioc容器中
注意***************************
最终结构目录:
Controller层代码
package com.xzh.controller; /**
* @Author XuZhuHong
* @CreateTime 2021/6/1 12:08
*/
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzh.bean.Employee;
import com.xzh.bean.Msg;
import com.xzh.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 处理crud
*/
@Controller
public class EmployeeController {
@Autowired
EmployeeService employeeService;
//根据id删除员工方法
@ResponseBody
@RequestMapping(value = "/emp/{ids}", method = RequestMethod.DELETE)
public Msg deleteEmployee(@PathVariable("ids") String ids) {
if (ids.contains("-")) {
//批量删除
List<Integer> list_ids=new ArrayList<>();
String[] split = ids.split("-");
for (String s : split) {
list_ids.add(Integer.parseInt(s));
}
employeeService.deleteEmps(list_ids);
} else {
//单个删除
employeeService.deleteEmp(Integer.parseInt(ids));
}
return Msg.success();
}
//修改员工信息
@ResponseBody
@RequestMapping(value = "/emp/{empId}", method = RequestMethod.PUT)
public Msg saveEmp(Employee employee) {
System.out.println(employee);
employeeService.updateEmp(employee);
return Msg.success();
}
//查询员工的信息方法
@ResponseBody
@RequestMapping(value = "/emp/{id}", method = RequestMethod.GET)
//PathVariable注解用来绑定restful 风格所绑定的数据
//里面的值对应{}里面的值
public Msg getEmp(@PathVariable("id") Integer id) {
Employee employee = employeeService.getEmp(id);
return Msg.success().add("emp", employee);
}
//检查用户名是否可用
@RequestMapping("/checkuser")
@ResponseBody
public Msg checkuser(String empName) {
//判断用户名是不是合法的表达式
String regex = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5})";
boolean matches = empName.matches(regex);
if (!matches) {
return Msg.fail().add("va_msg", "用户名必须是6-12位英文或者2-5个汉字");
}
boolean b = employeeService.checkUser(empName);
if (b) {
return Msg.success();
} else {
return Msg.fail().add("va_msg", "用户名已存在");
}
}
//保存员工信息
@RequestMapping(value = "/emp", method = RequestMethod.POST)
@ResponseBody
public Msg saveEmp(@Valid Employee employee, BindingResult result) {
//创建一个集合 然后把错误信息装进去
Map< String, Object > map = new HashMap<>();
//如果有失败的信息就封装进去
if (result.hasErrors()) {
//校验失败返回信息 在模态框中返回校验失败的信息
List< FieldError > fieldErrors = result.getFieldErrors();
for (FieldError fieldError : fieldErrors) {
//循环保存
map.put(fieldError.getField(), fieldError.getDefaultMessage());
}
//添加到msg中
return Msg.fail().add("errorFields", map);
} else {
//校验成功就返回
employeeService.saveEmp(employee);
return Msg.success();
}
}
/**
* ajax查询员工信息
*
* @param pn
* @param model
* @return
*/
@RequestMapping("/emps")
@ResponseBody
public Msg getEmpsWidthJson(@RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model) {
//这是一个分页查询
//引入分页插件
//在查询之前调用 startPage(页码,每页显示)
PageHelper.startPage(pn, 5);
List< Employee > emps = employeeService.getAll();
//将上面查询到的数据进行封装到分页中
//new PageInfo<>(查询到的数据,连续显示的页数)
PageInfo pageInfo = new PageInfo(emps, 5);
//分页中的每一条数据用 pageInfo.list()可以取出
return Msg.success().add("pageInfo", pageInfo);
}
/**
* 查询员工数据
*
* @return
*/
// @RequestMapping("/emps")
public String getEmps(@RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model) {
//这是一个分页查询
//引入分页插件
//在查询之前调用 startPage(页码,每页显示)
PageHelper.startPage(pn, 5);
List< Employee > emps = employeeService.getAll();
//将上面查询到的数据进行封装到分页中
//new PageInfo<>(查询到的数据,连续显示的页数)
PageInfo pageInfo = new PageInfo(emps, 5);
model.addAttribute("pageInfo", pageInfo);
//分页中的每一条数据用 pageInfo.list()可以取出
return "list";
}
}
主页面的代码:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: Admin
Date: 2021/6/1
Time: 12:09
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>员工页面</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"
integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ"
crossorigin="anonymous"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
crossorigin="anonymous"></script>
<%--用ajax请求 获取服务器的数据并且呈现到页面上--%>
<script type="text/javascript">
//总记录数
var totalRecor, currentPage;
//页面加载完成后
$(function () {
//进入这个页面就去首页
to_page(1)
//绑定新增按钮单机事件
//打开模态框
$("#emp_add_modal_btn").click(function () {
//模块弹出前清空表单所有数据
reset_form("#empaddModal form");
//发送Ajax请求显示部门信息再显示在下拉列表中
getDepts("#dept_add_select");
$("#empAddModal").modal({
backdrop: "static",
});
})
//新增按钮里 保存按钮的方法:
$("#emp_save_btn").click(function () {
//首先进行 前端数据校验
if (!validate_add_form()) {
return false;
}
//后端校验数据变化是否合理
if ($(this).attr("ajax-va") == "error") {
return false;
}
//所有校验成功后进行保存请求
$.ajax({
url: "${APP_PATH}/SSM/emp",
type: "post",
data: $("#empAddModal form").serialize(),
success: function (result) {
//后端再次校验
//返回的值是不是成功的值如果是就执行下面的操作
if (result.code == 100) {
//关闭模态框
$("#empAddModal").modal('hide');
//显示最后一页
to_page(totalRecord)
} else {
//失败后就显示失败的信息 从返回的参数中获取
if (undefined != result.extend.errorFields.gender) {
//邮箱的错误信息
show_validate_msg("#email_add_input", "1", result.extend.errorFields.gender);
}
if (undefined != result.extend.errorFields.empName) {
//员工的错误信息
show_validate_msg("#empName_add_input", "1", esult.extend.errorFields.empName);
}
}
}
})
})
//校验用户名是否可用 empName改变就检查
$("#empName_add_input").change(function () {
$.ajax({
url: "${APP_PATH}/SSM/checkuser",
type: "get",
data: "empName=" + this.value,
success: function (result) {
if (result.code == 100) {
//提示可用信息 并且给下一步校验做一个可用
show_validate_msg("#empName_add_input", "success", "用户名可用");
$("#emp_save_btn").attr("ajax-va", "success");
} else {
//提示不可用信息 并且给下一步校验做一个不可用
show_validate_msg("#empName_add_input", "1", result.extend.va_msg);
$("#emp_save_btn").attr("ajax-va", "error");
}
}
})
})
//编辑按钮的点击事件 用on绑定
$(document).on("click", ".edit_btn", function () {
//模块弹出前清空表单所有数据
reset_form("#empUpateModal form");
//发送Ajax请求显示部门信息再显示在下拉列表中
getDepts("#dept_update_select");
//查询员工数据显示在新窗口中
getEmp($(this).attr("edit-id"));
//把这个的id传送给这个里面更新按钮的id
$("#emp_update_btn").attr("edit-id", $(this).attr("edit-id"));
$("#empUpateModal").modal({
backdrop: "static",
})
})
//编辑里面 更新按钮的操作
$("#emp_update_btn").click(function () {
//校验邮箱是否正确
var empEmail = $("#email_update_input").val();
var regEmail = /^[a-z\d]+(\.[a-z\d]+)*@([\da-z](-[\da-z])?)+(\.{1,3}[a-z]+)+$/
if (!regEmail.test(empEmail)) {
// alert("邮箱不合法");
show_validate_msg("#email_update_input", "1", "邮箱不合法(前端3)");
return false;
} else {
show_validate_msg("#email_update_input", "success", "");
}
//成功过后 发送请求保存这个数据
$.ajax({
url: "${APP_PATH}/SSM/emp/" + $(this).attr("edit-id"),
type: "PUT",
data: $("#empUpateModal form").serialize(),
success: function (result) {
// alert(result.msg)
//关闭模态框
$("#empUpateModal").modal('hide');
//回到本页面
to_page(currentPage)
}
})
})
//删除按钮的操作
$(document).on("click", ".delete_btn", function () {
//弹出确认删除框
var empName = $(this).parents("tr").find("td:eq(2)").text()
if (confirm("确认删除" + empName)) {
$.ajax({
url: "${APP_PATH}/SSM/emp/" + $(this).attr("del-id"),
type: "DELETE",
success: function (result) {
// alert(result.msg)
to_page(currentPage)
}
})
}
})
//多选框(全选)单击事件
$("#check_all").click(function () {
//dom用prop获取
//attr获取自定义
$(".check_item").prop("checked", $("#check_all").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","");
}
})
//批量删除的单击事件
$("#emp_delete_all_btn").click(function () {
var empNames="";
var del_idstr="";
$.each($(".check_item:checked"),function () {
empNames+=$(this).parents("tr").find("td:eq(2)").text()+",";
del_idstr+=$(this).parents("tr").find("td:eq(1)").text()+"-";
});
//删除多余的逗号
empNames= empNames.substring(0,empNames.length-1);
//删除最后一个 "-"
del_idstr= del_idstr.substring(0,del_idstr.length-1);
if (confirm("确认删除这些人:"+empNames)){
//发送ajax
$.ajax({
url: "${APP_PATH}/SSM/emp/" + del_idstr,
type: "DELETE",
success: function (result) {
// alert(result.msg)
to_page(currentPage)
}
})
}else{
empNames="";
del_idstr="";
}
})
})
//查询员工信息的方法:
function getEmp(id) {
$.ajax({
url: "${APP_PATH}/SSM/emp/" + id,
type: "GET",
success: function (result) {
$("#empName_update_input").text(result.extend.emp.empName);
$("#email_update_input").val(result.extend.emp.email);
$("#empUpateModal input[name=gender]").val([result.extend.emp.gender])
$("#empUpateModal select").val([result.extend.emp.dId])
}
})
}
//模块弹出的清空表单方法
function reset_form(ele) {
//清空表单
$(ele)[0].reset();
//清空class
$(ele).find("*").removeClass("has-success has-error");
//清空提示框
$(ele).find(".help-block").text("");
//清空下拉框
$("#dept_add_select").empty();
}
//前端 数据校验方法
function validate_add_form() {
//拿到数据:
var empName = $("#empName_add_input").val();
var regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/
if (!regName.test(empName)) {
// alert("用户名可以是2- 5位中文或者6- 16位英文和数字的组合");
show_validate_msg("#empName_add_input", "1", "用户名可以是2- 5位中文或者6- 16位英文和数字的组合");
return false;
} else {
show_validate_msg("#empName_add_input", "success", "");
}
var empEmail = $("#email_add_input").val();
var regEmail = /^[a-z\d]+(\.[a-z\d]+)*@([\da-z](-[\da-z])?)+(\.{1,2}[a-z]+)$/
if (!regEmail.test(empEmail)) {
// alert("邮箱不合法");
show_validate_msg("#email_add_input", "1", "邮箱不合法(前端2)");
return false;
} else {
show_validate_msg("#email_add_input", "success", "");
}
return true;
}
//数据校验的通用显示方法
function show_validate_msg(ele, status, msg) {
//清除当前元素的校验状态
$(ele).parent().removeClass("has-success has-error");
$(ele).next("span").text("");
//提示主要的消息
if (status == "success") {
$(ele).parent().addClass("has-success");
$(ele).next("span").text(msg);
} else {
$(ele).parent().addClass("has-error");
$(ele).next("span").text(msg);
}
}
//跳转页码的Ajax请求
function to_page(pn) {
$.ajax({
url: "${APP_PATH}/SSM/emps",
data: "pn=" + pn,
type: "GET",
success: function (result) {
//解析员工数据
build_emps_table(result);
//分页数据
build_page_info(result);
/*分页数据*/
build_page_nav(result);
//给总记录数赋值:
totalRecord = result.extend.pageInfo.total;
}
})
}
//*查出部门信息 并且添加
function getDepts(ele) {
$(ele).empty()
$.ajax({
url: "${APP_PATH}/SSM/depts",
type: "GET",
success: function (result) {
var depts = result.extend.depts;
$.each(depts, function (index, item) {
$("<option></option>").append(item.deptName).attr("value", item.deptId).appendTo($(ele))
})
}
})
}
//*员工数据
function build_emps_table(result) {
//传入数据前清空当前数据 不然会重复显示
$("#emps_table tbody").empty();
//从传入的参数中得到emps的数据
var emps = result.extend.pageInfo.list;
$.each(emps, function (index, item) {
//jQuery里面放一个标签的话是创建标签的方法
// append方法是加入其他元素到里面
// addclass方法是给标签添加class
//appendto是把这个元素添加到哪里
var checkBoxTd = $("<td><input type='checkbox' class='check_item'/></td> ");
var empIdTd = $("<td></td>").append(item.empId);
var empNameTd = $("<td></td>").append(item.empName);
var genderTd = $("<td></td>").append(item.gender == "M" ? "男" : "女");
var emailTd = $("<td></td>").append(item.email);
var departmentTd = $("<td></td>").append(item.department.deptName);
//编辑按钮
var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn").append($("<span></span>").addClass("glyphicon glyphicon-pencil ")).append("编辑")
editBtn.attr("edit-id", item.empId)
//删除按钮
var delBtn = $("<button></button>").addClass("btn btn-danger btn-sm delete_btn").append($("<span></span>").addClass("glyphicon glyphicon-trash ")).append("删除")
delBtn.attr("del-id", item.empId)
//添加到一个单元格中
var btnTd = $("<td></td>").append(editBtn).append(delBtn)
//append()方法 执行完成后还是返回原来的数据
$("<tr></tr>")
.append(checkBoxTd)
.append(empIdTd)
.append(empNameTd)
.append(genderTd)
.append(emailTd)
.append(departmentTd)
.append(btnTd)
.appendTo("#emps_table tbody");
})
}
//*分页信息
function build_page_info(result) {
$("#page_info_area").empty();
$("#page_info_area").append("当前" + result.extend.pageInfo.pageNum + "页,总" + result.extend.pageInfo.pages + "共页,总共" + result.extend.pageInfo.total + "条记录")
//保存当前的页码
currentPage = result.extend.pageInfo.pageNum;
}
//*分页数据
function build_page_nav(result) {
$("#page_nav_area").empty();
var ul = $("<ul></ul>").addClass("pagination");
// 构建首页 上一页
var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href", "#"));
var prePageLi = $("<li></li>").append($("<a></a>").append("«"));
//判断还有没有上一页
if (!result.extend.pageInfo.hasPreviousPage) {
firstPageLi.addClass("disabled");
prePageLi.addClass("disabled");
} else {
//添加单击事件
firstPageLi.click(function () {
to_page(1)
})
prePageLi.click(function () {
to_page(result.extend.pageInfo.prePage)
})
}
//添加到ul中
ul.append(firstPageLi).append(prePageLi);
//遍历页码号码
$.each(result.extend.pageInfo.navigatepageNums, function (index, item) {
var numLi = $("<li></li>").append($("<a></a>").append(item));
if (result.extend.pageInfo.pageNum == item) {
numLi.addClass("active");
}
numLi.click(function () {
to_page(item);
})
ul.append(numLi);
})
//构建 下一页 末页
var nextPageLi = $("<li></li>").append($("<a></a>").append("»"));
var lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr("href", "#"));
if (!result.extend.pageInfo.hasNextPage) {
nextPageLi.addClass("disabled");
lastPageLi.addClass("disabled");
} else {
//添加单击事件
nextPageLi.click(function () {
to_page(result.extend.pageInfo.nextPage)
})
lastPageLi.click(function () {
to_page(result.extend.pageInfo.pages)
})
}
//添加到ul中
ul.append(nextPageLi).append(lastPageLi);
//上面的操作是 把分页条的所有数据添加到ul中
//添加到分页标签中
var nvaEle = $("<nav></nav>").append(ul).attr("aria-label", "Page navigation");
nvaEle.appendTo($("#page_nav_area"));
}
</script>
</head>
<body>
<%--添加方法模态框--%>
<!-- Modal -->
<div class="modal fade" id="empAddModal" 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">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">员工添加</h4>
</div>
<div class="modal-body">
<%--弹窗的显示的东西--%>
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">empName</label>
<div class="col-sm-10">
<input type="text" name="empName" class="form-control" id="empName_add_input"
placeholder="empName">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">email</label>
<div class="col-sm-10">
<input type="text" name="email" class="form-control" id="email_add_input"
placeholder="email@xzh.com">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">gender</label>
<div class="col-sm-10">
<label class="radio-inline">
<input type="radio" name="gender" id="gender1_add_input" value="M" checked="checked"> 男
</label>
<label class="radio-inline">
<input type="radio" name="gender" id="gender2_add_input" value="F"> 女
</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">department</label>
<div class="col-sm-4">
<%--这里面查询数据后部门再显示--%>
<select class="form-control" name="dId" id="dept_add_select">
</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="emp_save_btn">保存</button>
</div>
</div>
</div>
</div>
<%--修改方法模态框--%>
<!-- Modal -->
<div class="modal fade" id="empUpateModal" 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">×</span>
</button>
<h4 class="modal-title">修改</h4>
</div>
<div class="modal-body">
<%--弹窗的显示的东西--%>
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">empName</label>
<div class="col-sm-10">
<p class="form-control-static" name="empName" id="empName_update_input"></p>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">email</label>
<div class="col-sm-10">
<input type="text" name="email" class="form-control" id="email_update_input"
placeholder="email@xzh.com">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">gender</label>
<div class="col-sm-10">
<label class="radio-inline">
<input type="radio" name="gender" id="gender1_update_input" value="M" checked="checked">
男
</label>
<label class="radio-inline">
<input type="radio" name="gender" id="gender2_update_input" value="F"> 女
</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">department</label>
<div class="col-sm-4">
<%--这里面查询数据后部门再显示--%>
<select class="form-control" name="dId" id="dept_update_select">
</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="emp_update_btn">更新</button>
</div>
</div>
</div>
</div>
<%--数据显示--%>
<%
pageContext.setAttribute("APP_PATH", request.getContextPath());%>
<div class="container">
<%--标题--%>
<div class="row">
<div class="col-md-12">
<h1>SSM-CRUD</h1>
</div>
</div>
<%--按钮--%>
<div class="row">
<div class="col-md-4 col-md-offset-8">
<button class="btn btn-primary" id="emp_add_modal_btn">新增</button>
<button class="btn btn-danger" id="emp_delete_all_btn">删除</button>
</div>
</div>
<%--表格--%>
<div class="row">
<div class="col-md-12">
<table class="table table-hover" id="emps_table">
<thead>
<tr>
<th><input type="checkbox" id="check_all"></th>
<th>ID</th>
<th>姓名</th>
<th>性别</th>
<th>邮箱</th>
<th>部门</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<%--这里是动态显示员工共数据的--%>
</tbody>
</table>
</div>
</div>
<%--分页--%>
<div class="row">
<%--分页信息--%>
<div class="col-md-6" id="page_info_area">
</div>
<%--分页条--%>
<div class="col-md-6" id="page_nav_area">
</div>
</div>
</div>
</body>
</html>
项目全部代码:
链接: https://pan.baidu.com/s/1PeBH0aJV60yI1LHwAsLFtQ
提取码: audu