zoukankan      html  css  js  c++  java
  • bootstrap+Ajax+SSM(maven搭建)实现增删改查

     

    https://www.jianshu.com/p/d76316b48e3e

    功能点:

    • 分页
    • 数据校验
    • ajax
    • Rest风格的URI:使用HTTP协议请求方式的动词,来表示对资源的操作(GET(查询),POST(新增),PUT(修改),DELETE(删除))

    技术点

    • 基础框架-ssm
    • 数据库mysql
    • 前端框架-bootstrap
    • 项目依赖 -Maven
    • 分页 -pagehelper
    • 逆向工程-Mybatis Generator

    实现效果

     

     
    添加按钮弹出模态框

     
    编辑按钮弹出模态框

     
    删除

    基础环境搭建

    1)新建一个maven工程

     

     

     

     
    生成后的样子

     

    如果发现没有自动生成,在下图maven Project点击刷新按钮
     

    在main下新建一个java文件夹,并且右键make as source root


     

    2)引入项目依赖的jar包

    • springMVC
      打开http://mvnrepository.com/
      搜索Spring Web MVC

       

      选择了4.3.12.RELEASE
       

      复制里面的内容到pom.xml
       
    • jdbc


       

       
      选择同样的版本

       

      -Spring面向切面


       

       
      同样的版本
    • mybtatis


       

       
      任意一个版本
    • mybatis整合spring的适配包


       

       

       
    • 数据库连接池,驱动包


       
      c3p0要注意不能选错

       
    • mysql驱动


       

       

       
    • jstl


       
      注意要选对

       
    • servlet API


       

       

      整个pom.xml如下:

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.crud</groupId>
      <artifactId>crud</artifactId>
      <packaging>war</packaging>
      <version>1.0-SNAPSHOT</version>
      <name>crud Maven Webapp</name>
      <url>http://maven.apache.org</url>
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
          <!--引入项目依赖的jar包 -->
          <!--SpringMVC、Spring -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>4.3.12.RELEASE</version>
        </dependency>
          <!--spring jdbc -->
          <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-jdbc</artifactId>
              <version>4.3.12.RELEASE</version>
          </dependency>
    
          <!--spring面向切面 spring aspect -->
          <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-aspects</artifactId>
              <version>4.3.12.RELEASE</version>
          </dependency>
    
          <!--Mybatis -->
          <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
          <dependency>
              <groupId>org.mybatis</groupId>
              <artifactId>mybatis</artifactId>
              <version>3.4.5</version>
          </dependency>
          <!--mybatis和spring整合包 -->
          <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
          <dependency>
              <groupId>org.mybatis</groupId>
              <artifactId>mybatis-spring</artifactId>
              <version>1.3.0</version>
          </dependency>
          <!--c3p0数据库连接池-->
          <!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
          <dependency>
              <groupId>c3p0</groupId>
              <artifactId>c3p0</artifactId>
              <version>0.9.1.2</version>
          </dependency>
    
          <!--mysql驱动 -->
          <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
          <dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
              <version>6.0.6</version>
          </dependency>
          <!--JSTL -->
          <!-- https://mvnrepository.com/artifact/jstl/jstl -->
          <dependency>
              <groupId>jstl</groupId>
              <artifactId>jstl</artifactId>
              <version>1.2</version>
          </dependency>
          <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
          <dependency>
              <groupId>javax.servlet</groupId>
              <artifactId>servlet-api</artifactId>
              <version>2.5</version>
              <scope>provided</scope>
          </dependency>
      </dependencies>
      <build>
        <finalName>crud</finalName>
      </build>
    </project>
    
    

    3.引入bootstrap

    http://v3.bootcss.com/getting-started/#download

     
    选择最左边的如图所示下载

    将下载的内容复制到项目中:
     
    图片.png

    将jquery引入项目
     

    在index.html文件中引入样式
    <html>
    <head>
        <!--引入jquery -->
        <script src="static/js/jquery-3.2.1.min.js"></script>
        <!-- 引入样式-->
        <link href="static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
        <script src="static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    </head>
    <body>
    <h2>Hello World!</h2>
    </body>
    </html>
    

    4.SSM整合部分的配置文件(与02节相同稍作修改即可)

     
    项目架构

    1)mybatis
    sqlMapConfig.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>
        <!-- 全局setting,根据配置添加-->
    
        <!--配置别名-->
        <typeAliases>
            <!-- 批量扫描的别名-->
            <package name="com.chinglee.ssm.pojo"/>
    
        </typeAliases>
        
    </configuration>
    

    2)spring
    applicationContext-dao.xml

    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
        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-3.2.xsd 
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-3.2.xsd 
            http://www.springframework.org/schema/aop 
            http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
    
        <!-- 加载db.properties文件中的内容,db.properties文件中key命名要有一定的特殊规则 -->
        <context:property-placeholder location="classpath:db.properties" />
        <!-- 配置数据源 ,dhcp-->
        <!--
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
            destroy-method="close">
            <property name="driverClassName" value="${jdbc.driver}" />
            <property name="url" value="${jdbc.url}" />
            <property name="username" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />
            <property name="maxActive" value="30" />
            <property name="maxIdle" value="5" />
        </bean>
        -->
        <!-- 这里使用c3p0数据源-->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
              destroy-method="close">
            <property name="driverClass" value="${jdbc.driver}" />
            <property name="jdbcUrl" value="${jdbc.url}" />
            <property name="user" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />
        </bean>
    
        <!-- sqlSessionFactory -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 数据库连接池 -->
            <property name="dataSource" ref="dataSource" />
            <!-- 加载mybatis的全局配置文件 -->
            <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
        </bean>
        <!-- mapper扫描器 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 -->
            <property name="basePackage" value="com.chinglee.ssm.mapper"></property>
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        </bean>
    
    
    
    
    </beans>
    

    applicationContext-service.xml

    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
           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-3.2.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
    
      <!-- 用户的service-->
      <!--<bean id="userService" class="com.chinglee.ssm.serviceImpl.UserServiceImpl"/>-->
    
    
    </beans>
    

    applicationContext-transaction.xml

    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
           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-3.2.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
    
      <!-- 事务管理器
         对mybatis操作数据库控制,spring使用jdbc的事务控制类
      -->
      <bean id="TransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
          <!-- 数据源-->
        <property name="dataSource" ref="dataSource"/>
      </bean>
        <!-- 通知-->
        <tx:advice id="txAdvice" transaction-manager="TransactionManager">
             <tx:attributes>
                 <tx:method name="save" propagation="REQUIRED"/>
                 <tx:method name="delete" propagation="REQUIRED"/>
                 <tx:method name="insert" propagation="REQUIRED"/>
                 <tx:method name="update" propagation="REQUIRED"/>
                 <tx:method name="find" propagation="SUPPORTS" read-only="true"/>
    
             </tx:attributes>
        </tx:advice>
    
        <!--aop配置 -->
        <aop:config>
            <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.changqing.ssm.serviceImpl.*.*(..)  )"/>
        </aop:config>
    </beans>
    

    springmvc.xml

    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
           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-3.2.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
    
    <!--组件扫描 -->
        <context:component-scan base-package="com.changqing.ssm.controller"/>
        <!-- mvc注解驱动-->
        <mvc:annotation-driven></mvc:annotation-driven>
        <!--视图解析器
         解析jsp,默认使用jstl标签,classpath下的需要有jstl包
         -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!--配置jsp路径的前缀 -->
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <!--配置jsp路径的后缀 -->
            <property name="suffix" value=".jsp"/>
        </bean>
        <!--将springMVC不能处理的请求交给tomcat -->
        <mvc:default-servlet-handler/>
    
    
    
    
    </beans>
    
    

    db.properties

    jdbc.driver=com.mysql.jdbc.Driver
    //换成自己的数据库
    jdbc.url=jdbc:mysql://localhost:3306/new_schema
    jdbc.username=root
    jdbc.password=19940905
    

    log4j.properties

    # Global logging configuration
    #u5728u5f00u53d1u73afu5883u4e0bu65e5u5fd7u7ea7u522bu8981u8bbeu7f6eu6210DEBUGuff0cu751fu4ea7u73afu5883u8bbeu7f6eu6210infou6216error
    log4j.rootLogger=DEBUG, stdout
    # Console output...
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
    

    web.xml

    <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >
    
    <web-app xmlns="http://java.sun.com/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
              http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
             version="3.1">
      <display-name>Archetype Created Web Application</display-name>
      <!-- 加载spring容器 -->
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
      </context-param>
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
    
      <!--springmvc配置前端控制器-->
      <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--contextConfigLocation配置springmvc
        配置springmvc加载的配置文件(配置处理器映射器、适配器等等)
        -->
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:spring/springmvc.xml</param-value>
        </init-param>
      </servlet>
    
      <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--
         第一种:*.action访问以action结尾由DispatcherServlet进行解析
         第二种:/,所有访问由DispatcherServlet进行解析,对于静态文件的解析需要配置不让DispatcherServlet进行解析
        -->
    
        <url-pattern>*.action</url-pattern>
      </servlet-mapping>
    
      <!--配置字符编码过滤器 ,一定放在所有编码之前-->
      <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>
    
      <!-- 使用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>
    
    </web-app>
    
    

    5.逆向工程将user表生成mapper

    数据库可以直接导入项目中的user.sql脚本。


     
    user.sql脚本
     
    new_schema数据库

     
    user数据表

    6.实现增删改查功能

    1)访问index.html页面
    2)页面加载完成后执行js脚本,js脚本发起异步请求获取用户数据。
    3)UserController接受请求,调用service查出员工数据,然后使用PageHelp插件,将数据分页。将得到的PageInfo对象作为ResponseBody返回。
    4)js将获得的数据解析显示到页面。

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>用户管理</title>
        <!--引入jquery -->
        <script src="./static/js/jquery-3.2.1.js"></script>
        <!-- 引入样式-->
        <link rel="stylesheet" href="./static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
        <script src="./static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
        <script type="text/javascript" src="./static/js/index.js"></script>
        <!--web.xml中如果你用的jsp1.2版本的DTD,默认EL是关闭的,必须开启 -->
        <!--@ page isELIgnored="false"%-->
    </head>
    <body>
    
    <!--使用bootstrap搭建页面 -->
    <div class="container">
        <!--标题 -->
        <div class="row">
            <div class="col-md-12">
                <h1>用户管理</h1>
            </div>
        </div>
        <!--按钮 -->
        <div class="row">
            <div class="col-md-4 col-md-offset-8 col-sm-4 col-sm-offset-8">
                <button class="btn btn-primary" id="user_add_modal_btn">新增</button>
                <button class="btn btn-danger" id="user_delete_all_btn">删除</button>
            </div>
        </div>
        <br>
        <!--显示表格数据 -->
        <div class="row">
            <div class="table-responsive col-md-12">
                <table class="table table-hover" id="users_table">
                    <thead>
                    <tr>
                        <th>
                            <input type="checkbox" id="check_all"/>
                        </th>
                        <th>流水号</th>
                        <th>姓名</th>
                        <th>性别</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 col-sm-6" id="page_info_area">
                当前第页,总共页,总共条记录
            </div>
            <!--分页导航条信息 -->
            <div class="col-md-6 col-sm-6" id="page_nav_area">
    
            </div>
        </div>
    </div>
    <!-- 添加用户弹出的模态框 -->
    <div class="modal fade" id="userAddModal" 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="userAddModalLabel">添加用户</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">姓名</label>
                            <div class="col-sm-10">
                                <input type="text" name="username" class="form-control" id="userName_add_input" placeholder="姓名2-16位中英文、数字">
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">密码</label>
                            <div class="col-sm-10">
                                <input type="password" name="password" class="form-control" id="userPassword_add_input"
                                       placeholder="密码是6-18位英文和数字的组合">
                                <span  class="help-block"></span>
                            </div>
                        </div>
    
                        <div class="form-group">
                            <label class="col-sm-2 control-label">性别</label>
                            <div class="col-sm-10">
                                <label class="radio-inline">
                                    <input type="radio" name="sex" id="sex1_add_input" value="男" checked="checked"> 男
                                </label>
                                <label class="radio-inline">
                                    <input type="radio" name="sex" id="sex2_add_input" value="女"> 女
                                </label>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">工号</label>
                            <div class="col-sm-10">
                                <input type="text" name="worknumber" class="form-control" id="worknumber_add_input" placeholder="请输入工号">
                                <span  class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">部门</label>
                            <div class="col-sm-10">
                                <input type="text" name="department" class="form-control" id="department_add_input" placeholder="请输入部门">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">权限</label>
                            <div class="col-sm-10">
                                <label class="radio-inline">
                                    <input type="radio" name="permission" id="permission1_add_input" value="管理员"> 管理员
                                </label>
                                <label class="radio-inline">
                                    <input type="radio" name="permission" id="permission2_add_input" value="普通用户" checked="checked"> 普通用户
                                </label>
                            </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="user_save_btn">保存</button>
                </div>
            </div>
        </div>
    </div>
    <!--修改用户弹出的模态框 -->
    <div class="modal fade" id="userReviseModal" 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="userReviseModalLabel">修改用户</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">姓名</label>
                            <div class="col-sm-10">
                                <input type="text" name="username" class="form-control" id="userName_revise_input" placeholder="姓名是2-5位中文或6-16位英文和数字的组合">
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">密码</label>
                            <div class="col-sm-10">
                                <input type="password" name="password" class="form-control" id="userPassword_revise_input"
                                       placeholder="密码是6-18位英文和数字的组合">
                                <span  class="help-block"></span>
                            </div>
                        </div>
    
                        <div class="form-group">
                            <label class="col-sm-2 control-label">性别</label>
                            <div class="col-sm-10">
                                <label class="radio-inline">
                                    <input type="radio" name="sex" id="sex1_revise_input" value="男" checked="checked"> 男
                                </label>
                                <label class="radio-inline">
                                    <input type="radio" name="sex" id="sex2_revise_input" value="女"> 女
                                </label>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">工号</label>
                            <div class="col-sm-10">
                                <input type="text" name="worknumber" class="form-control" id="worknumber_revise_input" placeholder="请输入工号">
                                <span  class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">部门</label>
                            <div class="col-sm-10">
                                <input type="text" name="department" class="form-control" id="department_revise_input" placeholder="请输入部门">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">权限</label>
                            <div class="col-sm-10">
                                <label class="radio-inline">
                                    <input type="radio" name="permission" id="permission1_revise_input" value="管理员"> 管理员
                                </label>
                                <label class="radio-inline">
                                    <input type="radio" name="permission" id="permission2_revise_input" value="普通用户" checked="checked"> 普通用户
                                </label>
                            </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="user_revise_btn">修改</button>
                </div>
            </div>
        </div>
    </div>
    </body>
    </html>
    
     
    • 创建UserServce接口及实现类UserServiceImpl


       

      UserService接口中定义查询用户的方法:

    public interface UserService {
        public List<User> getAllUser();
    
        void saveUser(User user);
    
        Boolean checkUserName(String userName);
    
        void updateUser(User user);
    
        void deleteUser(Integer id);
    
        void deleteBatchUser(List<Integer> useridList);
    }
    

    UserServiceImpl实现UserService接口

    public class UserServiceImpl implements UserService {
        @Autowired
        UserMapper userMapper;
    
        /*
            查询所有员工
         */
        public List<User> getAllUser() {
            return userMapper.selectByExample(null);
        }
    
        /**
         * 保存员工信息
         * @param user
         */
        public void saveUser(User user) {
            userMapper.insertSelective(user);
        }
    
        /**
         * 校验用户名是否存在
         * @param userName
         * 数据库没有这条记录,count==0,返回true
         */
        public Boolean checkUserName(String userName) {
            UserExample example=new UserExample();
            UserExample.Criteria criteria=example.createCriteria();
            criteria.andUsernameEqualTo(userName);
            long count=userMapper.countByExample(example);
            return count==0;
        }
    
        /**
         * 员工更新方法
         * @param user
         */
        public void updateUser(User user) {
            userMapper.updateByPrimaryKeySelective(user);
        }
    
        /**
         * 员工删除方法(单个)
         * @param id
         */
        public void deleteUser(Integer id) {
            userMapper.deleteByPrimaryKey(id);
        }
    
        /**
         * 员工批量删除
         * @param useridList
         */
        public void deleteBatchUser(List<Integer> useridList) {
            UserExample example=new UserExample();
            UserExample.Criteria criteria=example.createCriteria();
            criteria.andUseridIn(useridList);
            userMapper.deleteByExample(example);
        }
    }
    
    
    • 引入分页插件
      在pom.xml中引入分页所需的包
      <!--引入分页插件-->
          <dependency>
              <groupId>com.github.pagehelper</groupId>
              <artifactId>pagehelper</artifactId>
              <version>5.0.4</version>
          </dependency>
    
          <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
          <dependency>
              <groupId>com.fasterxml.jackson.core</groupId>
              <artifactId>jackson-databind</artifactId>
              <version>2.9.0</version>
          </dependency>
    <!--
    报错org.apache.ibatis.binding.BindingException
    如果你的项目是maven项目,请你在编译后,到接口所在目录看一看,
    很有可能是没有生产对应的xml文件,因为maven默认是不编译的,因此,
    你需要在你的pom.xml的<build></build>里面,加这么一段:-->
      <build>
        <finalName>crud</finalName>
          <resources>
              <resource>
                  <directory>src/main/java</directory>
                  <includes>
                      <include>**/*.xml</include>
                  </includes>
                  <filtering>true</filtering>
              </resource>
          </resources>
      </build>
    

    sqlMapConfig中添加分页插件

    <!--引入分页插件 -->
        <plugins>
            <plugin interceptor="com.github.pagehelper.PageInterceptor">
                <!--分页合理化 -->
                <property name="reasonable" value="true"/>
            </plugin>
        </plugins>
    
    
    • UserController控制器实现


       
    /**
     * 处理员工的增删改查
     */
    
    @Controller
    public class UserController {
         @Autowired
        private UserService userService;
    
        /**
         * 使用Ajax方式,返回json数据,获得所有数据库用户信息
         * @param pn
         * @return
         * 需要引入jackson包
         */
        @RequestMapping(value = "/users",method = RequestMethod.GET)
        @ResponseBody
        public Msg getUsersWithJson(@RequestParam(value = "pn",defaultValue="1")Integer pn){
            //这是一个分页查询
            //引入PageHelp分页插件
            //在查询之前只需要调用,传入页码,以及每页的大小
            PageHelper.startPage(pn,8);
            //startPage后面紧跟的查询就是分页查询
            List<User> userList= userService.getAllUser();
            //使用pageInfo包装查询后的结果,只需要将pageInfo交给页面就行了。
            //封装了详细的分页信息,传入连续显示的页数
            PageInfo pageInfo=new PageInfo(userList,5);
            return Msg.sucess().add("pageInfo",pageInfo);
        }
    
        /**
         * 用户保存
         * @return
         */
       @RequestMapping(value = "/users",method = RequestMethod.POST)
       @ResponseBody
       public Msg saveUser(@Valid User user, BindingResult result){
           if(result.hasErrors()){
              //校验失败,返回失败,模态框中显示失败
               Map<String,Object> map=new HashMap<String,Object>();
               List<FieldError> errors=result.getFieldErrors();
               for(FieldError fieldError:errors){
                   System.out.println("错误的字段名"+fieldError.getField());
                   System.out.println("错误信息"+fieldError.getDefaultMessage());
                   map.put(fieldError.getField(),fieldError.getDefaultMessage());
               }
               return Msg.fail().add("errorFields",map);
           }else {
               userService.saveUser(user);
               return Msg.sucess();
           }
    
       }
    
        /**
         * 校验用户名
         */
        @RequestMapping(value = "/checkUser")
        @ResponseBody
        public Msg checkUserName(@RequestParam("userName") String userName){
            boolean b=userService.checkUserName(userName);
            if(b){
                return Msg.sucess();
            }else {
               return Msg.fail();
            }
    
        }
    
        /**
         * 修改员工信息(更新)
         */
    
        @RequestMapping(value = "/users/{userid}",method = RequestMethod.PUT)
        @ResponseBody
        public Msg updateUser(User user){
            System.out.print(user);
            userService.updateUser(user);
             return Msg.sucess();
         }
    
    
        /**
         * 删除员工信息
         *
         */
        @RequestMapping(value = "/users/{del_idstr}",method = RequestMethod.DELETE)
        @ResponseBody
        public Msg deleteUser(@PathVariable("del_idstr")String del_idstr){
            //批量删除
            if(del_idstr.contains("-")){
                List<Integer> useridList=new ArrayList<Integer>();
              String[] str_ids=del_idstr.split("-");
              for(String id_str:str_ids){
                  useridList.add(Integer.parseInt(id_str));
              }
              userService.deleteBatchUser(useridList);
            }
            //单个删除
            else {
                Integer userid=Integer.parseInt(del_idstr);
                userService.deleteUser(userid);
            }
    
            return Msg.sucess();
        }
    
    
    }
    
    

    Msg类:表示返回的json信息


     
    /**
     * 返回json格式数据通用类
     */
    public class Msg {
        //状态码 100-成功 200-失败
        private int code;
        //提示信息
        private String message;
        //用户要返回给浏览器的数据
        private Map<String,Object> extend=new HashMap<String, Object>();
    
        public static Msg sucess(){
            Msg result=new Msg();
            result.setCode(100);
            result.setMessage("处理成功");
            return result;
        }
        public static Msg fail(){
            Msg result=new Msg();
            result.setCode(200);
            result.setMessage("处理失败");
            return result;
        }
        public Msg add(String key,Object value){
            this.getExtend().put(key,value);
            return this;
        }
        public int getCode() {
            return code;
        }
    
        public void setCode(int code) {
            this.code = code;
        }
    
        public String getMessage() {
            return message;
        }
    
        public void setMessage(String message) {
            this.message = message;
        }
    
        public Map<String, Object> getExtend() {
            return extend;
        }
    
        public void setExtend(Map<String, Object> extend) {
            this.extend = extend;
        }
    }
    
    • index.js实现
    //1.页面加载完成之后发送Ajax请求,要到分页数据
    
    $(function () {
        var totalRecord,currentPage;
        //显示第一页
        to_page(1);
        //添加员工
        addUser();
        //修改用户
        reviseUser();
        //单个删除用户
        deleteUser();
        //批量删除
        deleteSomeUser();
    
    
    
    
        /**
         * 1.实现用户信息展示
         * @param pn
         */
       //显示员工信息
        function to_page(pn) {
            $.ajax({
                url: "/users.action",
                data: "pn=" + pn,
                type: "GET",
                success: function (result) {
                    //1.解析并显示员工数据
                    build_users_table(result);
                    //2.解析并显示分页信息
                    build_page_info(result);
                    //3.解析并显示分页条数据
                    build_page_nav(result);
    
                }
            })
        }
        //解析并显示员工数据表
        function build_users_table(result) {
            //清空table表格
            $("#users_table tbody").empty();
            var users = result.extend.pageInfo.list;
            //遍历元素users
            $.each(users, function (index, item) {
                var checkBox=$("<td><input type='checkbox' class='check_item'/></td>");
                var userId = $("<td></td>").append(item.userid);
                var userName = $("<td></td>").append(item.username);
                var password = $("<td></td>").append(item.password);
                var permission = $("<td></td>").append(item.permission);
                var depatment = $("<td></td>").append(item.department);
                var worknumber = $("<td></td>").append(item.worknumber);
                var sex = $("<td></td>").append(item.sex);
    
                var button1 = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn").append($("<span></span>").addClass("glyphicon glyphicon-pencil").attr("aria-hidden", true)).append("编辑");
                var button2 = $("<button></button>").addClass("tn btn-danger btn-sm delete_btn").append($("<span></span>").addClass("glyphicon glyphicon-trash").attr("aria-hidden", true)).append("删除");
                var td_btn = $("<td></td>").append(button1).append(" ").append(button2);
                $("<tr></tr>").append(checkBox).append(userId).append(userName).append(sex).append(worknumber).append(depatment)
                    .append(permission).append(password).append(td_btn ).appendTo("#users_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 + "条记录");
            totalRecord = 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("&laquo;").attr("href", "#"));
            var nextPageLi = $("<li></li>").append($("<a></a>").append("&raquo;").attr("href", "#"));
            var lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr("href", "#"));
            //如果没有前一页,前一页和首页就不能点
            if (result.extend.pageInfo.hasPreviousPage == false) {
                firstPageLi.addClass("disabled");
                prePageLi.addClass("disabled");
            } else {
                //首页
                firstPageLi.click(function () {
                    to_page(1);
                });
                prePageLi.click(function () {
                    to_page(result.extend.pageInfo.pageNum - 1);
                });
            }
            if (result.extend.pageInfo.hasNextPage == false) {
                nextPageLi.addClass("disabled");
                lastPageLi.addClass("disabled");
            } else {
                //构建点击事件
    
                nextPageLi.click(function () {
                    to_page(result.extend.pageInfo.pageNum + 1);
                });
                lastPageLi.click(function () {
                    to_page(result.extend.pageInfo.lastPage);
                })
            }
            //添加首页和前一页
            ul.append(firstPageLi).append(prePageLi);
            //遍历添加页码
            $.each(result.extend.pageInfo.navigatepageNums, function (index, item) {
                var numLi = $("<li></li>").append($("<a></a>").append(item).attr("href", "#"));
                //如果是当前选中页面,添加active标识
                if (result.extend.pageInfo.pageNum == item) {
                    numLi.addClass("active");
                }
                //给每个页码添加点击就跳转
                numLi.click(function () {
                    to_page(item);
                });
                ul.append(numLi);
            });
            //添加下一页和末页
            ul.append(nextPageLi).append(lastPageLi);
            var navEle = $("<nav></nav>").append(ul);
            navEle.appendTo("#page_nav_area");
    
    
        }
    
    
    
    
    
    
        /**
         * 2.实现新增功能
         * @returns {boolean}
         */
        function addUser() {
    
            //为新增按钮添加modal
            $("#user_add_modal_btn").click(function () {
                //清除表单数据
                $("#userAddModal form")[0].reset();
                $("#userName_add_input").next("span").text("");
                $("#userAddModal").modal({
                    backdrop: "static"
                })
            });
    
            //校验该用户是否存在,如果存在就不能添加该用户
            $("#userName_add_input").change(function () {
                var userName = $("#userName_add_input").val();
                //发送Ajax请求校验姓名是否可用
                $.ajax({
                    url: "/checkUser.action",
                    data: "userName=" + userName,
                    type: "GET",
                    success: function (result) {
                        //表示成功,用户名可用
                        if (result.code == 100) {
                            show_validate_msg($("#userName_add_input"), "success", "");
                            //为保存按钮添加属性
                            $("#user_save_btn").attr("ajax-va", "success");
                        } else if (result.code == 200) {
                            show_validate_msg($("#userName_add_input"), "error", "该员工姓名已存在");
                            $("#user_save_btn").attr("ajax-va", "error");
                        }
                    }
                })
            });
    
            //保存用户信息
            $("#user_save_btn").click(function () {
                //先校验表单信息
                if (!validate_form( $("#userName_add_input"),$("#userPassword_add_input"),$("#worknumber_add_input"))) {
                    return false;
                }
                //1.判断之前的ajax用户名校验是否成功
                if ($(this).attr("ajax-va") == "error") {
                    return false;
                }
                //2.发送ajax请求保存员工
                $.ajax({
                    url: "/users.action",
                    type: "POST",
                    data: $("#userAddModal form").serialize(),
                    success: function (result) {
                        //员工保存成功(后端校验)
                        if (result.code == 100) {
                            //1.关闭modal框
                            $("#userAddModal").modal('hide');
                            //2.来到最后一页,显示刚才保存的数据
                            to_page(totalRecord);
                        } else {
                            //显示失败信息(后端校验)
                            if (result.extend.errorFields.username != undefined) {
                                show_validate_msg($("#userName_add_input"), "error", result.extend.errorFields.username);
                            }
                            if (result.extend.errorFields.password != undefined) {
                                show_validate_msg($("#userPassword_add_input"), "error", result.extend.errorFields.password);
                            }
                            if (result.extend.errorFields.worknumber != undefined) {
                                show_validate_msg($("#worknumber_add_input"), "error", result.extend.errorFields.worknumber);
                            }
    
                        }
    
                    }
                });
            });
    
        }
    
        //校验表单信息是否满足正则要求
        function validate_form(Name_ele,password_ele,worknumber_ele) {
            //1.拿到要校验的数据,使用正则表达式
            //校验姓名
            var userName = Name_ele.val();
            //|(^[u2E80-u9FFF]{2,5})
            var regName = /^[a-zA-Z0-9u2E80-u9FFF]{2,16}$/;
            //如果验证失败
            if (!regName.test(userName)) {
                show_validate_msg(Name_ele, "error", "姓名2-16位中英文、数字");
                return false;
            } else {
                show_validate_msg(Name_ele, "success", "");
            }
            //检验密码
            var password = password_ele.val();
            var regPass = /^[a-zA-Z0-9_-]{6,18}$/;
            if (!regPass.test(password)) {
                show_validate_msg(password_ele, "error", "密码是6-18位英文、数字");
                return false;
            } else {
                show_validate_msg(password_ele, "success", "");
            }
    
            //检验工号
            var workNumber =worknumber_ele.val();
            var regWork = /^[a-zA-Z0-9]{3,18}$/;
            if (!regWork.test(workNumber)) {
                show_validate_msg(worknumber_ele, "error", "工号是3-18位英文、数字");
                return false;
            } else {
                show_validate_msg(worknumber_ele, "success", "");
            }
            return true;
        }
        //显示校验提示信息
        function show_validate_msg(ele, status, msg) {
            //清除当前元素校验状态
            $(ele).parent().removeClass("has-error has-success");
            $(ele).next("span").text("");
            if (status == "error") {
                ele.parent().addClass("has-error");
                ele.next("span").text(msg);
            } else if (status == "success") {
                ele.parent().addClass("has-success");
                ele.next("span").text(msg);
            }
    
        }
    
    
        /**
         * 3.修改用户
         */
        function reviseUser() {
            //为编辑按钮绑定弹出modal框事件
            //1.因为在按钮创建之前就绑定了click,所以用普通click方法绑定不上
    
            $(document).on("click",".edit_btn",function () {
                //清除表单数据
                $("#userReviseModal form")[0].reset();
                $("#userName_revise_input").next("span").text("");
    
               //修改框中用户信息回显
               var id= $(this).parent().parent().children("td").eq(1).text();
               //将id的值传递给修改按钮的属性,方便发送Ajax请求
                $("#user_revise_btn").attr("edit-id",id);
               var name=$(this).parent().parent().children("td").eq(2).text();
               var sex=$(this).parent().parent().children("td").eq(3).text();
               var worknumber=$(this).parent().parent().children("td").eq(4).text();
               var depart=$(this).parent().parent().children("td").eq(5).text();
               var permission=$(this).parent().parent().children("td").eq(6).text();
               var password=$(this).parent().parent().children("td").eq(7).text();
                $("#userName_revise_input").val(name);
                $("#worknumber_revise_input").val(worknumber);
                $("#department_revise_input").val(depart);
                $("#userPassword_revise_input").val(password);
                $("#userReviseModal input[name=sex]").val([sex]);
                $("#userReviseModal input[name=permission]").val([permission]);
                $("#userReviseModal").modal({
                    backdrop: "static"
                })
            });
            //2.为模态框中的修改按钮绑定事件,更新员工信息
            $("#user_revise_btn").click(function () {
              //1.更新之前进行表单验证,验证没通过就直接返回
                if(!validate_form( $("#userName_revise_input"),$("#userPassword_revise_input"),$("#worknumber_revise_input"))){
                    return false;
                }
                //2.验证通过后发送ajax请求保存更新的员工数据
                //如果要直接发送PUT之类的请求
                //在WEB.xml配置HttpPutFormContentFilter过滤器即可
                //这里未使用如上所述方法
                $.ajax({
                    url:"/users/"+$(this).attr("edit-id")+".action",
                    type:"POST",
                    data:$("#userReviseModal form").serialize()+"&_method=PUT",
                    success:function (result) {
                        //1.关闭modal框
                        $("#userReviseModal").modal('hide');
                        //2.来到当前页,显示刚才保存的数据
                        to_page(currentPage);
                        
                    }
                })
    
            })
        }
    
    
        /**
         * 4.删除用户
         */
        function deleteUser() {
            $(document).on("click",".delete_btn",function () {
                //1.弹出确认删除对话框
                var username=$(this).parents("tr").find("td:eq(2)").text();
                var userid=$(this).parents("tr").find("td:eq(1)").text();
                if(confirm("确认删除【"+username+"】吗?")){
                    //确认,发送ajax请求删除
                    $.ajax({
                        url:"/users/"+userid+".action",
                        type:"DELETE",
                        success:function (result) {
                            alert(result.message);
                            to_page(currentPage);
                        }
                    })
    
    
                }
            })
        }
    
    
        /**
         * 5.批量删除
         */
        function deleteSomeUser() {
            //1.实现全选全不选
            //attr获取checked是undefined
            //对于dom原生的属性要用prop读取和修改
            $("#check_all").click(function () {
                $(".check_item").prop("checked",$(this).prop("checked"));
            })
    
            //check_item
            $(document).on("click",".check_item",function () {
                //判断当前选中的条目个数
               var flag= $(".check_item:checked").length==$(".check_item").length;
               $("#check_all").prop("checked",flag);
            })
    
            //为批量删除按钮添加点击事件
            $("#user_delete_all_btn").click(function () {
                var userNames="";
                var del_idstr="";
                $.each($(".check_item:checked"),function () {
                   userNames+=$(this).parents("tr").find("td:eq(2)").text()+",";
                   //组装员工id字符串
                    del_idstr+=$(this).parents("tr").find("td:eq(1)").text()+"-";
                });
                userNames=userNames.substring(0,userNames.length-1);
                del_idstr=del_idstr.substring(0,del_idstr.length-1);
                if(confirm("确认删除【"+userNames+"】吗")){
                    //发送Ajax请求
                    $.ajax({
                        url:"/users/"+del_idstr+".action",
                        type:"DELETE",
                        success:function (result) {
                            alert(result.message);
                            to_page(currentPage);
                        }
    
                    });
                }
    
            })
    
        }
    
    
    });
    
  • 相关阅读:
    使用JavaWeb实现文件的上传和下载
    IDEA使用Maven创建Web项目的两种方式
    Window10系统下联想笔记本进入BIOS界面方法
    MarkDown语法
    PV-UV-QPS
    expect 安装 salt 客户端
    fg、bg、jobs、&、nohup、ctrl+z、ctrl+c 命令
    查看CPU 内存 硬盘 网络 查看进程使用的文件 uptime top ps -aux vmstat iostat iotop nload iptraf nethogs
    rpm 命令使用 和 lsof -p 1406 使用
    salt 执行shell 脚本 修改名字
  • 原文地址:https://www.cnblogs.com/yelanggu/p/10205047.html
Copyright © 2011-2022 走看看