码迷,mamicode.com
首页 > Web开发 > 详细

bootstrap+Ajax+SSM(maven搭建)表单增删改查

时间:2018-09-22 14:27:39      阅读:726      评论:0      收藏:0      [点我收藏+]

标签:用户信息   oct   数字   ash   active   cat   offset   rate   deny   

前后端分离,前端利用ajax调用后端API接收json数据,进行表单的增删改查

软件架构

  • IDE:IDEA
  • 数据库:mysql
  • jdk:1.8
  • tomcat:9
  • 后端:springmvc,mybatis
  • 前端:bootstrap

项目地址:https://gitee.com/smfx1314/ssm-demo

效果图:

技术分享图片

项目结构:

技术分享图片

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.ssm.demo</groupId>
  <artifactId>ssm-demo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>ssm-demo Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>

    <org.springframework.version>4.2.4.RELEASE</org.springframework.version>
    <java.version>1.8</java.version>
    <mybatis.version>3.2.5</mybatis.version>
    <mybatis-spring.version>1.2.2</mybatis-spring.version>
    <jdbc.driver.version>5.1.38</jdbc.driver.version>
    <aspectj.version>1.7.4</aspectj.version>
    <javax.servlet-api.version>3.1.0</javax.servlet-api.version>
    <jsp-api.version>2.2</jsp-api.version>
    <jstl.version>1.2</jstl.version>
    <com.alibaba.druid.version>1.0.25</com.alibaba.druid.version>
    <com.google.gson.version>2.7</com.google.gson.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!-- 3.Spring -->
    <!-- 1)Spring核心 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <!-- 2)Spring DAO层 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <!-- 3)Spring web -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <!-- 4)Spring test -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <!-- Map工具类 -->
    <dependency>
      <groupId>commons-collections</groupId>
      <artifactId>commons-collections</artifactId>
      <version>3.2.2</version>
    </dependency>
    <!--文件上传工具-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.2</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.5</version>
    </dependency>

    <!-- Begin: 数据库依赖包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${jdbc.driver.version}</version>
      <scope>runtime</scope>
    </dependency>
    <!-- End: 数据库依赖包 -->

    <!--druid==>阿里巴巴数据库连接池-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>${com.alibaba.druid.version}</version>
    </dependency>

    <!--json-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.5.2</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.5.2</version>
    </dependency>

    <!-- Begin: mybatis依赖 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>${mybatis-spring.version}</version>
    </dependency>
    <!-- End: mybatis依赖 -->

      <!--引入分页插件-->
      <dependency>
          <groupId>com.github.pagehelper</groupId>
          <artifactId>pagehelper</artifactId>
          <version>5.1.2</version>
      </dependency>

    <!-- Begin: aspectj相关jar包-->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>${aspectj.version}</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>${aspectj.version}</version>
    </dependency>
    <!-- End: aspectj相关jar包-->

      <!-- Begin: Servlet相关依赖包 -->
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>${javax.servlet-api.version}</version>
          <scope>provided</scope>
      </dependency>
      <dependency>
          <groupId>javax.servlet.jsp</groupId>
          <artifactId>jsp-api</artifactId>
          <version>${jsp-api.version}</version>
      </dependency>

    <!-- 2.Servlet web -->
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
      <!-- End: Servlet相关依赖包 -->

      <!--json数据格式-->
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
          <version>2.8.5</version>
      </dependency>
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-annotations</artifactId>
          <version>2.8.5</version>
      </dependency>
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.8.5</version>
      </dependency>

    <!--excle导入导出-->
    <!--<dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>easyexcel</artifactId>
      <version>1.0.2</version>
    </dependency>-->
  </dependencies>

  <build>
    <finalName>ssm-demo</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.6.1</version>
          <configuration>
            <!-- <source>1.8</source> 源代码使用的开发版本 <target>1.8</target> 需要生成的目标class文件的编译版本 -->
            <encoding>utf-8</encoding>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

首先是配置文件,applicationContext.xml,springmvc.xml,mybatis-config.xml,web.xml

applicationContext

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                     http://www.springframework.org/schema/beans/spring-beans.xsd 
                     http://www.springframework.org/schema/tx 
                     http://www.springframework.org/schema/tx/spring-tx.xsd 
                     http://www.springframework.org/schema/aop 
                     http://www.springframework.org/schema/aop/spring-aop.xsd
                     http://www.springframework.org/schema/context 
                     http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 自动扫描 -->
    <context:component-scan base-package="com.ssm.dao"/>
    <context:component-scan base-package="com.ssm.service"/>

    <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/ssm-demo"/>
        <!-- 改为你的地址即可 -->
        <property name="username" value="root"/>
        <property name="password" value="1234"/>
    </bean>

    <!--配置SessionFactoryBean-->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="mapperLocations" value="classpath:mappers/*.xml"></property>
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
    </bean>

    <!--Mapper接口扫描:DAO接口所在包名,Spring会自动查找其下的类-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.ssm.dao"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"></property>
    </bean>

    <!--事务管理transaction manager-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--开启注解事务-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

springmvc.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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
    <!-- 使用注解的包,包括子集 -->
    <context:component-scan base-package="com.ssm.controller"/>

    <!--两个标配-->
    <!-- 解决映射器处理器和映射器适配器 -->
    <mvc:annotation-driven/>
    <!-- 处理静态资源 -->
    <mvc:default-servlet-handler/>
    <!-- 视图解析器 这里可以不用配置,因为是通过ajax异步调用,本人习惯配置上,根据需要更改-->
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"></property>
    </bean>
</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>
       <!-- Globally enables or disables any caches configured in any mapper under this configuration -->
       <setting name="cacheEnabled" value="false"/>
       <!-- Sets the number of seconds the driver will wait for a response from the database -->
       <setting name="defaultStatementTimeout" value="5"/>
       <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
       <setting name="mapUnderscoreToCamelCase" value="true"/>
       <!-- Allows JDBC support for generated keys. A compatible driver is required.
       This setting forces generated keys to be used if set to true,
        as some drivers deny compatibility but still work -->
       <setting name="useGeneratedKeys" value="true"/>
   </settings>

   <!-- Continue editing here -->
   <typeAliases>
       <package name="com.ssm.entity"/>
   </typeAliases>
   <!-- 引入 pageHelper插件 -->
   <plugins>
       <plugin interceptor="com.github.pagehelper.PageInterceptor">
           <!--reasonable:分页合理化参数,默认值为false。
               当该参数设置为 true 时,pageNum<=0 时会查询第一页,
               pageNum>pages(超过总数时),会查询最后一页。
               默认false 时,直接根据参数进行查询。-->
           <property name="reasonable" value="true"/>
       </plugin>
   </plugins>
</configuration>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:web="http://java.sun.com/xml/ns/javaee" xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">
  <display-name>Archetype Created Web Application</display-name>

  <!--Start 欢迎页-->
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <!--End 欢迎页-->

  <!--Start spring监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--End Start spring监听器 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <!--Start 编码过滤器 解决乱码问题-->
  <filter>
    <filter-name>encodingFilter</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>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!--End 编码过滤器 解决乱码问题-->

  <!--Start spring mvc servlet-->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!--End servlet-mapping -->

  <!--druid ==> WEB方式监控配置-->
  <servlet>
    <servlet-name>DruidStatView</servlet-name>
    <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>DruidStatView</servlet-name>
    <url-pattern>/druid/*</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>druidWebStatFilter</filter-name>
    <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
    <init-param>
      <param-name>exclusions</param-name>
      <param-value>/public/*,*.js,*.css,/druid*,*.jsp,*.swf</param-value>
    </init-param>
    <init-param>
      <param-name>principalSessionName</param-name>
      <param-value>sessionInfo</param-value>
    </init-param>
    <init-param>
      <param-name>profileEnable</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>druidWebStatFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

实体类

User

package com.ssm.entity;

import com.alibaba.excel.metadata.BaseRowModel;

import java.io.Serializable;

/**
 * Created by jiangfeixiang on 2018/9/4
 * @author smfx1314
 *
 */
public class User extends BaseRowModel implements Serializable {

    private Integer id;
    
    private String username;

    private String sex;

    private String city;

    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", sex='" + sex + '\'' +
                ", city='" + city + '\'' +
                ", age=" + age +
                '}';
    }
}

dao层

UserMapper接口

package com.ssm.dao;

import com.ssm.entity.User;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by jiangfeixiang on 2018/9/4
 * @author smfx1314
 */
@Repository
public interface UserMapper {

    /**
     * 查询所有用户
     * @return
     */
    List<User> getAllUser();

    /**
     *
     * @param username
     * @return
     */
    User checkUserName(String username);

    /**
     * 保存用户
     * @param user
     * @return
     */
    int saveUser(User user);

    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    int deleteUser(Integer id);

    /**
     * 修改用户
     * @param user
     */
    void updateUser(User user);
}

对应的UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.ssm.dao.UserMapper" >
  <!--<resultMap id="BaseResultMap" type="User" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
  </resultMap>-->

    <!--查询所有用户-->
  <select id="getAllUser" resultType="User">
    SELECT * FROM USER
  </select>

  <!--根据用户名查询,校验用户名-->
  <select id="checkUserName" resultType="User" parameterType="String">
    SELECT * FROM USER WHERE username=#{username}
  </select>

  <!--保存用户-->
  <insert id="saveUser" parameterType="User">
      INSERT INTO USER(username,sex,city,age) VALUES(#{username},#{sex},#{city},#{age})
  </insert>

  <!--修改用户-->
  <update id="updateUser" parameterType="User">
    UPDATE USER SET username=#{username},sex=#{sex},city=#{city},age=#{age} WHERE id=#{id}
  </update>

  <!--根据id删除用户-->
  <delete id="deleteUser" parameterType="Integer">
      DELETE FROM USER WHERE id=#{id}
  </delete>
</mapper>

service层

UserService接口

package com.ssm.service;

import com.ssm.entity.User;

import java.util.List;

/**
 * Created by jiangfeixiang on 2018/9/4
 */
public interface UserService {

    /**
     * 返回所有用户
     * @return
     */
    List<User> getAllUser();

    /**
     * 校验用户名
     * @param username
     * @return
     */
    User checkUserName(String username);

    /**
     * 保存用户
     * @param user
     * @return
     */
    int saveUser(User user);

    /**
     * 删除用户根据id
     * @param id
     * @return
     */
    int deleteUser(Integer id);

    /**
     * 修改用户
     * @param user
     */
    void updateUser(User user);
}

UserServiceImpl实现类

package com.ssm.service.impl;

import com.ssm.dao.UserMapper;
import com.ssm.entity.User;
import com.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by jiangfeixiang on 2018/9/4
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 查询所有用户
     * @return
     */
    @Override
    public List<User> getAllUser() {
        List<User> allUser = userMapper.getAllUser();
        return allUser;
    }

    /**
     * 校验用户名
     * @param username
     * @return
     */
    @Override
    public User checkUserName(String username) {

        return userMapper.checkUserName(username);
    }

    /**
     * 保存用户
     * @param user
     * @return
     */
    @Override
    public int saveUser(User user) {
        int i = userMapper.saveUser(user);
        return i;
    }

    /**
     * 修改用户
     */
    @Override
    public void updateUser(User user) {

        userMapper.updateUser(user);
    }

    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    @Override
    public int deleteUser(Integer id) {

        return  userMapper.deleteUser(id);
    }

}

Controller层

UserController

package com.ssm.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.common.ResultData;
import com.ssm.entity.User;
import com.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jiangfeixiang on 2018/9/4
 * @author
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;


    /**
     *这里统一返回ResultData封装的json数据格式,不在用Map<String,Object>形式了
     * @return
     */
    @RequestMapping(value = "/getAllUser",method = RequestMethod.GET)
    @ResponseBody
    public ResultData getAllUser(@RequestParam(defaultValue="1",required=true,value="pn") Integer pn){
        Map<String, Object> map = new HashMap<>();
        /**
         * 每页显示记录数
         *
         */
        Integer pageSize=5;
        /**
         * 分页查询,注意顺序,startPage()方法放前面
         */
        PageHelper.startPage(pn, pageSize);
        /**
         * 获取所用用户信息
         */
        List<User> allUser = userService.getAllUser();
        /**
         * 使用pageInfo包装查询后的结果,只需要将pageInfo交给页面就行了。
         * 封装了详细的分页信息,传入连续显示的页数
         */
        PageInfo<User> pageInfo=new PageInfo(allUser);
//        map.put("code",100);
//        map.put("msg","成功");
//        map.put("pageInfo",pageInfo);
        //return map;
       return ResultData.success(pageInfo);

    }

    /**
     * 校验用户名
     * @param username
     * @return
     */
    @RequestMapping(value = "/checkUser/{username}",method = RequestMethod.POST)
    @ResponseBody
    public ResultData checkUserName(@PathVariable("username") String username){
        //校验用户名
        User user = userService.checkUserName(username);
        System.out.println(user);
        return ResultData.success(user);
    }

    /**
     * 保存用户信息
     * @param user
     * @return
     */
    @RequestMapping(value = "/saveUser",method = RequestMethod.POST)
    @ResponseBody
    public ResultData saveUser(@RequestBody User user){
       int i = userService.saveUser(user);
        return ResultData.success();
    }

    /**
     * 修改员工信息(更新)
     */

    @RequestMapping(value = "/updateUser",method = RequestMethod.POST)
    @ResponseBody
    public ResultData updateUser(@RequestBody User user){
        System.out.print(user);
        userService.updateUser(user);
        return ResultData.success();
    }

    /**
     * 根据id删除用户
     */
    @RequestMapping(value = "/deleteUser/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public ResultData deleteUser(@PathVariable("id")Integer id){
        //保存用户
        int i = userService.deleteUser(id);
        System.out.println(i);
        return ResultData.success();
    }
}

为了Controller统一返回json数据格式,所以封装了ResultData

ResultData

package com.ssm.common;

/**
 * @Author: 姜飞祥
 * @Description: 封装结果集成统一的json样式
 * @Date: Create in 2018/9/15 12:08
 * @param: $params$
 * @return: $returns$
 */
public class ResultData<T>{
    /**
     * 信息状态码,0表示成功,1表示失败
     */
    private Integer code;
    /**
     * 提示信息
     */
    private String msg;
    /**
     * 返回的对象,因为有分页信息,方便返回json数据见名之意,这里直接变量名为pageInfo。
     */
    private T pageInfo;

    /**
     * 成功时调用的函数
     * @param object 要返回的对象
     * @return
     */
    public static ResultData<Object> success(Object object) {
        ResultData result = new ResultData();
        result.setCode(200);
        result.setMsg("成功");
        result.setPageInfo(object);
        return result;
    }

    /**
     * 成功时,如果没有要返回的对象,调用此方法
     * @return
     */
    public static ResultData<Object> success() {
        ResultData result = new ResultData();
        result.setCode(200);
        result.setMsg("成功");
        result.setPageInfo(null);
        //return success(null);
        return result;
    }

    /**
     * 失败时调用的函数
     * @return
     */
    public static ResultData<Object> fail() {
        ResultData result = new ResultData();
        result.setCode(100);
        result.setMsg("失败");
        return result;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getPageInfo() {
        return pageInfo;
    }

    public void setPageInfo(T pageInfo) {
        this.pageInfo = pageInfo;
    }

    @Override
    public String toString() {
        return "ResultData{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", pageInfo=" + pageInfo +
                '}';
    }
}

下面是前端代码

  • bootstrap官网:https://v3.bootcss.com/getting-started/#download
    下载后整个复制到static下。
  • jquery官网:http://jquery.com/download/
    下载后复制到static>js下即可,并创建index.js文件

    index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <!--引入jquery -->
    <script src="./static/js/jquery-3.3.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>
</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-3 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>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 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">
                            <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="city" class="form-control" id="city_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="age" class="form-control" id="age_add_input" placeholder="请输入年龄">
                        </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">
                            <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="city" class="form-control" id="city_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="age" class="form-control" id="age_revise_input" placeholder="年龄">
                        </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>

index.js

$(function () {
    var totalRecord,currentPage;
    //1.显示所有数据
    to_page(1);
    //2.添加用户
    addUser();
    //3.修改用户
    reviseUser();
    //4.单个删除用户
    deleteUser();

    /**
     * 1.显示所用用户
     * @param pn
     */
    function to_page(pn) {

        $.ajax({
            url: "/user/getAllUser",
            data:"pn="+pn,
            type: "GET",
            dataType: "json",
            contentType:"application/json;charset=UTF-8",
            success: function (data) {
                //alert(data.msg);
                //解析并显示员工数据表
                build_users_table(data)

                //2.解析并显示分页信息
                build_page_info(data);

                //3.解析并显示分页条数据
                build_page_nav(data);
            }
        })
    }

    /**
     * 解析并显示员工数据表
     * @param data
     */
    function build_users_table(data) {
        //清空table表格
        $("#users_table tbody").empty();
        var users = data.pageInfo.list;

        //遍历元素
        $.each(users, function (index, item) {
            var checkBox=$("<td><input type='checkbox' class='check_item'/></td>");
            var id = $("<td></td>").append(item.id);
            var username = $("<td></td>").append(item.username);
            var sex = $("<td></td>").append(item.sex);
            var city = $("<td></td>").append(item.city);
            var age = $("<td></td>").append(item.age);

            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(id).append(username).append(sex).append(city).append(age)
                .append(td_btn ).appendTo("#users_table tbody");

        })
    }

    /**
     * 解析显示分页信息
     * @param data
     */
    function build_page_info(data) {
        $("#page_info_area").empty();
        $("#page_info_area").append("当前" + data.pageInfo.pageNum + "页,总共" + data.pageInfo.pages +
            "页,总共" + data.pageInfo.total + "条记录");
        totalRecord = data.pageInfo.total;
        currentPage=data.pageInfo.pageNum;
    }

    /**
     * 解析显示分页导航条
     * @param data
     */
    function build_page_nav(data) {
        $("#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 (data.pageInfo.hasPreviousPage == false) {
            firstPageLi.addClass("disabled");
            prePageLi.addClass("disabled");
        } else {
            //首页
            firstPageLi.click(function () {
                to_page(1);
            });
            prePageLi.click(function () {
                to_page(data.pageInfo.pageNum - 1);
            });
        }
        if (data.pageInfo.hasNextPage == false) {
            nextPageLi.addClass("disabled");
            lastPageLi.addClass("disabled");
        } else {
            //构建点击事件
            nextPageLi.click(function () {
                to_page(data.pageInfo.pageNum + 1);
            });
            lastPageLi.click(function () {
                to_page(data.pageInfo.lastPage);
            })
        }
        //添加首页和前一页
        ul.append(firstPageLi).append(prePageLi);
        //遍历添加页码
        $.each(data.pageInfo.navigatepageNums, function (index, item) {
            var numLi = $("<li></li>").append($("<a></a>").append(item).attr("href", "#"));
            //如果是当前选中页面,添加active标识
            if (data.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();
            $("#userAddModal").modal({
                backdrop: "static"
            })
        });

        /**
         * 2.保存用户信息
         * 校验该用户是否存在,如果存在就不能添加该用户
         */
        $("#username_add_input").change(function () {
            var username = $("#username_add_input").val();
            //发送Ajax请求校验姓名是否可用
            $.ajax({
                url: "/user/checkUser/"+username,
                //data: "username=" + username,
                type: "POST",
                success: function (data) {
                    //alert(data.pageInfo.username);
                    //表示成功,用户名可用
                    if (data.code == 200 && data.pageInfo != null) {
                        alert("用户名**"+ data.pageInfo.username +"**已经存在");
                        $("#user_save_btn").attr("ajax-va", "error");
                    }  else if (data.code == 200 && data.pageInfo == null) {
                        //为保存按钮添加属性
                        $("#user_save_btn").attr("ajax-va", "success");
                    }
                }
            })
        });

        /**
         * 保存用户信息
         */
        $("#user_save_btn").click(function () {
            var username = $("#username_add_input").val();
            var sex =$("input[name=sex]:checked").val();
            var city =$("#city_add_input").val();
            var age =$("#age_add_input").val();
            //2.发送ajax请求保存员工
            $.ajax({
                url: "/user/saveUser",
                type: "POST",
                data: JSON.stringify({username:username,sex:sex,city:city,age:age}),
                dataType:"json",
                contentType:"application/json;charset=UTF-8",
                success: function (data) {
                   if (data.code == 200){
                       //1.关闭modal框
                       $("#userAddModal").modal('hide');
                       //2.来到最后一页,显示刚才保存的数据
                       to_page(totalRecord);
                   }
                }
            });
        });
    }

    /**
     * 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 username=$(this).parent().parent().children("td").eq(2).text();
            var sex=$(this).parent().parent().children("td").eq(3).text();
            var city=$(this).parent().parent().children("td").eq(4).text();
            var age=$(this).parent().parent().children("td").eq(5).text();

            $("#username_revise_input").val(username);
            $("#userReviseModal input[name=sex]").val([sex]);
            $("#city_revise_input").val(city);
            $("#age_revise_input").val(age);
            $("#userReviseModal").modal({
                backdrop: "static"
            })
        });
        //2.为模态框中的修改按钮绑定事件,更新员工信息
        $("#user_revise_btn").click(function () {

            //2.验证通过后发送ajax请求保存更新的员工数据
            //如果要直接发送PUT之类的请求
            //在WEB.xml配置HttpPutFormContentFilter过滤器即可
            //这里未使用如上所述方法
            var id = $(this).attr("edit-id");
            var username = $("#username_revise_input").val();
            var sex = $("#userReviseModal input[name=sex]").val();
            var city =$("#city_revise_input").val();
            var age =$("#age_revise_input").val();
            $.ajax({
                url:"/user/updateUser",
                type:"POST",
                data:JSON.stringify({id:id,username:username,sex:sex,city:city,age:age}),
                dataType:"json",
                contentType:"application/json;charset=UTF-8",
                success:function () {
                    //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 id=$(this).parents("tr").find("td:eq(1)").text();
            if(confirm("确认删除【"+username+"】吗?")){
               // alert(id);
                //确认,发送ajax请求删除
                $.ajax({
                    url:"/user/deleteUser/"+id,
                    type:"DELETE",
                    success:function (data) {
                        alert(data.msg);
                        to_page(currentPage);
                    }
                })
            }
        })
    }
});

本文参考:https://www.jianshu.com/p/d76316b48e3e
如有疑问可联系

bootstrap+Ajax+SSM(maven搭建)表单增删改查

标签:用户信息   oct   数字   ash   active   cat   offset   rate   deny   

原文地址:https://www.cnblogs.com/smfx1314/p/9689817.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!