项目代码

项目代码:

实体类:

package com.openlab.bean;


public class Member {
    private Integer id;
    private String name;
    private Integer age;
    private String address;

    public Member() {
    }

    public Member(String name, Integer age, String address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Member{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                '}';
    }
}

package com.openlab.bean;

import java.util.List;

/**
 * @author mao on 2021/3/29.
 * @version 1.0 maozhijob@163.com
 */
public class Result {
    private int code;
    private String msg;

    public int getCode() {
        return code;
    }

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

    public String getMsg() {
        return msg;
    }

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

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public List<Member> getData() {
        return data;
    }

    public void setData(List<Member> data) {
        this.data = data;
    }

    private int count ;
    private List<Member> data;
}

controller:

package com.openlab.controller;


import com.openlab.bean.Member;

import com.openlab.bean.Result;
import com.openlab.service.IMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class MemberController {

    @Autowired
    IMember iMember;
    @RequestMapping(value = "/",method = RequestMethod.GET)
    public String index(){

        return "index";
    }
    @ResponseBody
    @RequestMapping(value = "/findByid",method = RequestMethod.GET)
    public Member findByid(Integer id){
        Member member = iMember.findById(id);
        return member;
    }
    @ResponseBody
    @RequestMapping(value = "/findAll",method = RequestMethod.GET)
    public Result findAll(){
        Result all = iMember.findAll();

        return all;
    }
    @ResponseBody
    @RequestMapping(value = "/updateByid",method = RequestMethod.GET)
    public Boolean updateByid(Member member){
        Boolean aBoolean = iMember.updateMember(member);
        return aBoolean;
    }
    @ResponseBody
    @RequestMapping(value = "/insert",method = RequestMethod.GET)
    public boolean insert(Member member){
        Boolean saveMember = iMember.saveMember(member);
        return saveMember;
    }
    @ResponseBody
    @RequestMapping(value = "/deleteByid",method = RequestMethod.GET)
    public boolean deleteByid(Integer id){
        Boolean saveMember = iMember.deleteById(id);
        return saveMember;
    }
}

DAO:

package com.openlab.dao;

import com.openlab.bean.Member;
import org.apache.ibatis.annotations.*;
import org.mybatis.spring.annotation.MapperScan;

import java.util.List;

/**
 * @author Administrator
 */
public interface MemberMapper {
    @Select("select * from member")
    List<Member> findAll();

    /**
     * @param id
     * @return
     */
    @Select("select * from member where id=#{id}")
    Member findById(Integer id);
    @Insert("insert into member (id,name,age,address) values(#{id},#{name},#{age},#{address})")
    Boolean saveMember(Member member);
    @Update({
            "<script> ",
            "update member set ",
            "<if test = \"name != null\"> ",
            " name=#{name}, ",
            "</if> ",
            "<if test = \"age != null\"> ",
            " age=#{age}, ",
            "</if> ",
            "<if test = \"address != null\"> ",
            " address=#{address} ",
            "</if> ",
            " WHERE id=#{id}",
            "</script>"
    })
    Boolean updateMember(Member member);
    @Delete("delete from member where id=#{id}")
    Boolean deleteById(@Param("id") Integer id);
}

Service:

package com.openlab.service;

import com.openlab.bean.Member;
import com.openlab.bean.Result;

import java.util.List;

public interface IMember {

    public Result findAll();

    public Member findById(Integer id);

    public Boolean saveMember(Member member);

    public Boolean updateMember(Member member);

    public Boolean deleteById(Integer id);
}

package com.openlab.service;

import com.openlab.bean.Member;
import com.openlab.bean.Result;
import com.openlab.dao.MemberMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class IMemberImpl implements IMember {
    @Autowired
    MemberMapper memberMapper;

    @Override
    public Result findAll() {
        Result re  = new Result();
        List<Member> list = memberMapper.findAll();
        re.setCode(0);
        re.setCount(list.size());
        re.setData(list);
        re.setMsg("查询成功");
        return re;
    }

    @Override
    public Member findById(Integer id) {
        return memberMapper.findById(id);
    }

    @Override
    public Boolean saveMember(Member member) {
        return memberMapper.saveMember(member);
    }

    @Override
    public Boolean updateMember(Member member) {
        return memberMapper.updateMember(member);
    }

    @Override
    public Boolean deleteById(Integer id) {
        return memberMapper.deleteById(id);
    }
}

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 开启注解扫描,要扫描的是service和dao层的注解,要忽略web层注解,因为web层让SpringMVC框架
去管理 -->
    <context:component-scan base-package="com.openlab">
        <!-- 配置要忽略的注解 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!-- 配置C3P0的连接池对象 -->
    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/projectmanager?serverTimezone=GMT" />
        <property name="username" value="root" />
        <property name="password" value="19991009" />
    </bean>
    <!-- 配置SqlSession的工厂 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:Mybatis.xml"/>
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--    &lt;!&ndash; 配置扫描dao的包 &ndash;&gt;-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.openlab.dao"/>
    </bean>

</beans>

Mybatis.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--mybatis主配置文件-->
<configuration>

</configuration>

SpringMVC.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 扫描controller的注解,别的不扫描 -->
    <context:component-scan base-package="com.openlab.controller">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!-- 开启对SpringMVC注解的支持 -->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <!-- 配置视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- HTml文件所在的目录 -->
        <property name="prefix" value="/templates/" />
        <!-- 文件的后缀名 -->
        <property name="suffix" value=".html" />
    </bean>
    <!-- 设置静态资源不过滤 -->
    <mvc:resources location="/WEB-INF/templates/" mapping="/templates/**" />
    <mvc:annotation-driven >
        <!-- 消息转换器 -->
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value="text/plain;charset=UTF-8"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
</beans>

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>
  <display-name>Archetype Created Web Application</display-name>
  <!--设置配置文件的路径-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!--解决中文乱码的过滤器-->
  <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>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!--配置前端控制器-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--加载springmvc.xml配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:SpringMVC.xml</param-value>
    </init-param>
    <!--启动服务器,创建该servlet-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

index.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>会员检索</title>
    <link rel="stylesheet" type="text/css" href="https://www.layuicdn.com/layui/css/layui.css"/>
</head>
<body>
<div class="layui-row layui-col-space10">
    <div class="layui-col-md4" style="margin-top: 16%">
        <table class="layui-hide" id="test"></table>
    </div>
    <div class="layui-col-md4" style="text-align: center;margin-top: 16%;">
        <form class="layui-form" lay-filter="example"> <!-- 提示:如果你不想用form,你可以换成div等任何一个普通元素 -->
            <div class="layui-form-item">
                <label class="layui-form-label">会员ID</label>
                <div class="layui-input-block">
                    <span>
                    <input type="text" name="id" id="id" placeholder="请输入" autocomplete="off" class="layui-input"
                           style="width: 80%; float:left;">
                    <button type="button" id="search" class="layui-btn layui-btn-radius layui-btn-normal"
                            style="width: 15%; float:right">检索</button>
                </span></div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">会员名</label>
                <div class="layui-input-block">
                    <input type="text" id="name" name="name" placeholder="请输入" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">年龄</label>
                <div class="layui-input-block">
                    <input type="text" id="age" name="age" placeholder="请输入" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">住址</label>
                <div class="layui-input-block">
                    <input type="text" id="address" name="address" placeholder="请输入" autocomplete="off"
                           class="layui-input">
                </div>
            </div>
            <!-- 更多表单结构排版请移步文档左侧【页面元素-表单】一项阅览 -->
        </form>
    </div>

    <div class="layui-col-md4" style="margin-top: 16%;">
        <div style="margin-left: 20%; ">
            <button type="button" id="insert" class="layui-btn layui-btn-radius">新增</button>
            <br>
            <button type="button" id="update" class="layui-btn layui-btn-radius layui-btn-warm" style="margin-top: 10%">
                更新
            </button>
            <br>
            <button type="button" id="delete" class="layui-btn layui-btn-radius layui-btn-danger"
                    style="margin-top: 10%">删除
            </button>
        </div>
    </div>
</div>

<script src="https://www.layuicdn.com/layui/layui.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
    layui.use(['form','table'], function () {
        var form = layui.form;
        var table = layui.table;
        //左侧表格
        table.render({
            elem: '#test'
            ,method: 'get'
            , url: '/findAll'
            , cellMinWidth: 80 //全局定义常规单元格的最小宽度,layui 2.2.1 新增
            , cols: [
                [
                    {field: 'id', title: '会员ID', sort: true}
                    , {field: 'name', title: '会员名'}
                    , {field: 'age', title: '年龄', sort: true}
                    , {field: 'address', title: '住址'}
                ]
            ]
        });
        //表单赋值
        $('#search').on('click', function () {
            console.log($("#id").val())
            if ($("#id").val() != '') {
                $.ajax({
                    url: '/findByid',
                    data: {"id": $("#id").val(),},
                    dataType: "json",
                    success: function (data) {
                        form.val('example', {
                            "name": data.name // "name": "value"
                            , "age": data.age
                            , "address": data.address
                        });
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        /*错误信息处理*/
                        layer.msg("查新出错,未找到该id")
                        form.val('example', {
                            "name": ''
                            , "age": ''
                            , "address": ''
                        });
                    }

                })

            } else {
                layer.msg("请填写会员id后在进行查询")
            }
        });

        //表单取值
        layui.$('#insert').on('click', function () {

            if ($("#id").val() === '' || $("#name").val() === '' || $("#age").val() === '' || $("#address").val() === '') {
                layer.msg("所有内容都不能为空!")
            } else {
                $.ajax({
                    url: '/insert',
                    data: {
                        "id": $("#id").val(),
                        "name": $("#name").val(),
                        "age": $("#age").val(),
                        "address": $("#address").val()
                    },
                    dataType: "json",
                    success: function (data) {
                        layer.msg("新增成功!")
                        //执行重载
                        table.reload('test', {
                            page: {
                                curr: 1 //重新从第 1 页开始
                            }
                        }, 'data');
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        /*错误信息处理*/
                        layer.msg("新增失败!")
                    }

                })
            }
        });
        layui.$('#update').on('click', function () {
            if ($("#id").val() === '') {
                layer.msg("更新会员ID不能为空!")
            } else {
                $.ajax({
                    url: '/updateByid',
                    data: {
                        "id": $("#id").val(),
                        "name": $("#name").val(),
                        "age": $("#age").val(),
                        "address": $("#address").val()
                    },
                    dataType: "json",
                    success: function (data) {
                        if(data){
                            layer.msg("更新成功!")
                            table.reload('test', {
                                page: {
                                    curr: 1 //重新从第 1 页开始
                                }
                            }, 'data');
                        }else {
                            layer.msg("更新失败")
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        /*错误信息处理*/
                        layer.msg("更新失败!")
                    }

                })
            }
        });
        layui.$('#delete').on('click', function () {
            if ($("#id").val() === '') {
                layer.msg("删除会员ID不能为空!")
            } else {
                $.ajax({
                    url: '/deleteByid',
                    data: {"id": $("#id").val()},
                    dataType: "json",
                    success: function (data) {
                        if(data){
                            layer.msg("删除成功!")
                            table.reload('test', {
                                page: {
                                    curr: 1 //重新从第 1 页开始
                                }
                            }, 'data');
                        }
                        else {
                            layer.msg("删除失败!")
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        /*错误信息处理*/
                        layer.msg("删除失败!")
                    }

                })
            }
        });

    });
</script>
</body>
</html>

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>org.example</groupId>
    <artifactId>demo1</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

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

    <properties>
        <spring.version>5.0.2.RELEASE</spring.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <mysql.version>8.0.23</mysql.version>
        <mybatis.version>3.4.5</mybatis.version>
        <jackson.version>2.9.8</jackson.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
<!--            <!- 注意版本这里整合spring5&ndash;&gt;-->
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.11.RELEASE</version>
        </dependency>

        <!-- spring -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- log end -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>demo1</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

sql文件:

/*
 Navicat Premium Data Transfer

 Source Server         : 本地
 Source Server Type    : MySQL
 Source Server Version : 50725
 Source Host           : localhost:3306
 Source Schema         : lanmoyun

 Target Server Type    : MySQL
 Target Server Version : 50725
 File Encoding         : 65001

 Date: 29/03/2021 15:23:34
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for member
-- ----------------------------
DROP TABLE IF EXISTS `member`;
CREATE TABLE `member`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `age` int(20) NULL DEFAULT NULL,
  `address` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of member
-- ----------------------------
INSERT INTO `member` VALUES (2, '张三', 23, '陕西');
INSERT INTO `member` VALUES (4, '张三', 23, '陕西');

SET FOREIGN_KEY_CHECKS = 1;

上一篇:Redis排序集合类型Sort Set


下一篇:SQL注入攻击技术(二)---注入分类