当先锋百科网

首页 1 2 3 4 5 6 7

1.ssm整合的原理

2.创建maven工程并配置

1)web更换为4.0,之前版本过低会出严重bug

2)引入所需依赖

 引入依赖

<dependencies>

    <!--引入pageHeler-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.3.0</version>
    </dependency>

    <!--spring-webmvc依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.15.RELEASE</version>
    </dependency>

    <!--mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.6</version>
    </dependency>

    <!--mybatis和spring整合的依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.6</version>
    </dependency>

    <!--mysql驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.28</version>
    </dependency>

    <!--druid连接池依赖-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.2.4</version>
    </dependency>

    <!--lombok依赖-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.24</version>
    </dependency>
    <!--jackson java对象转换为json对象 @ResponseBody-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.13.2.2</version>
    </dependency>
    <!--servlet-api依赖-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
    </dependency>

    <!--spring-jdbc依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.15.RELEASE</version>
    </dependency>

    <!--generator依赖-->
    <dependency>
      <groupId>org.mybatis.generator</groupId>
      <artifactId>mybatis-generator-core</artifactId>
      <version>1.4.0</version>
    </dependency>

    <!--junit单元测试依赖-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>compile</scope>
    </dependency>

  </dependencies>

3)spring配置文件


    <!--包扫描-->
    <context:component-scan base-package="com.zsy"/>

    <!--开启注解驱动-->
    <mvc:annotation-driven/>

    <!--放行静态资源-->
    <mvc:default-servlet-handler/>

    <!--配置数据源-->
    <bean id="ds" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai"/>
        <property name="username" value="root"/>
        <property name="password" value="1234"/>
        <property name="maxActive" value="20"/>
        <property name="minIdle" value="5"/>
        <property name="initialSize" value="5"/>
        <!--maxWait 最大等待时间 单位 毫秒-->
        <property name="maxWait" value="3000"/>
    </bean>

    <!--SqlSessionFactory 整合mybatis-->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="ds"/>
        <!--设置mybatis映射文件的路径-->
        <property name="mapperLocations" value="classpath:"/>
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor"></bean>
            </array>
        </property>
    </bean>

    <!--生成dao接口的代理实现类-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--为com.zsy.dao包下的接口生成代理实现类-->
        <property name="basePackage" value="com.zsy.dao"/>
    </bean>

4)web配置文件

 <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:appliction.xml</param-value>
        </init-param>
        <!--tomcat启动时创建DipatcherServlet 默认当访问controller路径时创建-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <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>

5)使用generator快速生成代码

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

<generatorConfiguration>
    <!--使用的mysql的jar包路径-->
    <classPathEntry location="E:\repMaven\mysql\mysql-connector-java\8.0.28\mysql-connector-java-8.0.28.jar" />

    <context id="DB2Tables" targetRuntime="MyBatis3">
        <!--抑制注释   suppressAllComments:抑制全部注释-->
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

        <!--数据源(库)的配置信息-->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai"
                        userId="root"
                        password="1234">
                        <property name="nullCatalogMeansCurrent" value="true" />
        </jdbcConnection>

        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!--java实体类的配置-->
        <javaModelGenerator targetPackage="com.zsy.entity" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!--映射文件的配置-->
        <sqlMapGenerator targetPackage="mapper"  targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!--dao数据访问层的配置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.zsy.dao"  targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!--数据库表和实体的映射关系
             schema:数据库名称
             tableName: 表名
             domainObjectName:实体类名

             enableCountByExample:是否生成复杂的添加操作
             enableUpdateByExample:是否生成复杂的修改操作
             enableSelectByExample:是否生成复杂的查询操作
             enableDeleteByExample:是否生成复杂的删除操作
        -->
        <table schema="mydb" tableName="tb_student" domainObjectName="Student"
               enableUpdateByExample="false" enableSelectByExample="false" enableDeleteByExample="false" enableCountByExample="false">

        </table>
        <!--<table schema="mydb" tableName="tbl_user" domainObjectName="User"
               enableUpdateByExample="false" enableSelectByExample="false" enableDeleteByExample="false" enableCountByExample="false">

        </table>-->

    </context>
</generatorConfiguration>

测试代码:

public class TestGenerator {

    @Test
    public void test02() throws Exception{
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("generator.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    }
}

使用 generator生成了dao、entity、mapper文件

3.实现主页面(查询)

service实体类层代码:

@Service
public class StudentServiceImpl implements StudentService {

    //交予spring管理
    @Autowired
    private StudentMapper sm;

    public PageInfo<Student> find(Integer currentPage, Integer pageSize,Map map) {
        PageHelper.startPage(currentPage,pageSize);
        List<Student> l = sm.findAll(map);
        PageInfo<Student> pageInfo = new PageInfo<Student>(l);
        return pageInfo;
    }
}

controller操作层代码:

@RestController
@RequestMapping("student")
public class StudentController {

    @Autowired
    private StudentService ss;

   
    //查询
    @RequestMapping("select")
    public CommonResult select(Integer currentPage, Integer pageSize, @RequestBody Map map){
        PageInfo<Student> lsit = ss.find(currentPage, pageSize,map);
        return new CommonResult(2000,"查询成功",lsit);
    }
}

前端界面代码:

<%--
  Created by IntelliJ IDEA.
  User: Z
  Date: 2022/6/15
  Time: 15:23
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <!--引入element得css样式-->
    <link rel="stylesheet" href="css/index.css" target="_blank" rel="external nofollow" >
    <!--引入vue得js文件 这个必须在element之前引入-->
    <script type="text/javascript" src="js/vue.js"></script>
    <script type="text/javascript" src="js/axios.min.js"></script>
    <script type="text/javascript" src="js/qs.min.js"></script>
    <!--element得js文件-->
    <script type="text/javascript" src="js/index.js"></script>
</head>
<body >
<!--创建一个标签使vue挂载到该标签上-->
<div id="app">
    <el-button type="primary" @click="addDialogVisible = true">添加</el-button>
    <el-button type="primary" @click="quit">退出</el-button>
    <%--搜索框--%>
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="姓名">
            <el-input v-model="searchForm.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item label="地址">
            <el-input v-model="searchForm.address" placeholder="地址"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>
        </el-form-item>
    </el-form>
    <el-dialog
            title="添加学生信息"
            :visible.sync="addDialogVisible"
            width="30%">
        <!--:model==绑定表单数据-->
        <el-form :model="addform" :rules="addRules" ref="addRuleForm">
            <el-form-item label="姓名" label-width="80px" prop="name">
                <el-input v-model="addform.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="地址" label-width="80px" prop="address">
                <el-input v-model="addform.address" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addStu">确 定</el-button>
  </span>
    </el-dialog>

    <el-dialog
            title="修改学生信息"
            :visible.sync="editDialogVisible"
            width="30%">
        <!--:model==绑定表单数据-->

        <el-form :model="editform" :rules="addRules" ref="editRuleForm">
            <el-form-item label="姓名" label-width="80px" prop="name">
                <el-input v-model="editform.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="地址" label-width="80px" prop="address">
                <el-input v-model="editform.address" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editStu">确 定</el-button>
        </span>
    </el-dialog>

    <el-table
            :data="tableData"
            border
            style="width: 100%">
        <el-table-column
                prop="id"
                label="学生编号"
        >
        </el-table-column>
        <el-table-column
                prop="name"
                label="学生姓名"
        >
        </el-table-column>
        <el-table-column
                prop="address"
                label="学生住址">
        </el-table-column>
        <el-table-column
                fixed="right"
                label="操作"
        >
            <template slot-scope="scope">
                <el-button @click="edit(scope.row)" type="success" size="small" icon="el-icon-edit" plain>编辑</el-button>
                <el-button type="danger"  size="small" icon="el-icon-delete" @click="del(scope.row.id)" plain>删除</el-button>
            </template>
        </el-table-column>


    </el-table>

    <%--
        分页组件
        size-change:页面显示条数改变时触发的事件
        current-change:页码改变时触发的事件
        current-page:当前的页面
        page-sizes:接受一个整型数组,数组元素为展示的选择每页显示个数的选项
        page-size:每页显示的条数
    --%>
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes=pageSizes
            :page-size=pageSize
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
    </el-pagination>
</div>
</body>
<script>
    var app = new Vue({
        el: "#app",
        data: {
            //搜索表单
            searchForm:{},
            //当前显示的页面变量
            currentPage:1,

            pageSizes:[5,10,15,20],
            pageSize:5,
            //总条数
            total:0,

            tableData: [],
            //对话框的显示和隐藏  如果为false则隐藏 如果为true则显示
            addDialogVisible: false,
            //添加表单的数据
            addform: {},
            //对话框的显示和隐藏  如果为false则隐藏 如果为true则显示
            editDialogVisible:false,
            //修改表单的数据
            editform:{},

            //定义添加表单数据的校验
            addRules: {
                name: [
                    {required: true, message: '姓名不能为空', trigger: 'blur'}
                ],
                age: [
                    {required: true, message: '年龄不能为空'},
                    {type: 'number', message: '年龄必须为数字'}
                ],
                address:[
                    {required: true, message: '地址不能为空'}
                ]
            }
        },
        //页面加载后执行
        created() {
            this.initTable();
        },
        methods: {
            //搜索按钮事件
            onSearch(){
                this.currentPage = 1;
                this.initTable()
            },

            //每页显示的条数大小改变时触发的方法
            handleSizeChange(val) {
                this.pageSize = val;
                this.initTable();
            },
            //页码改变时触发的方法
            handleCurrentChange(val) {
                this.currentPage = val;
                this.initTable();
            },

            //初始化表格数据
            initTable() {
                var that = this;
                axios.post("/student/select?currentPage="+
                    this.currentPage+"&pageSize="+
                    this.pageSize,this.searchForm).then(function (result) {
                    if (result.data.code === 2000) {
                        that.tableData = result.data.data.list;
                        that.total = result.data.data.total;
                    }
                })
            },
            del(id) {
                var that = this;
                var qs = Qs;
                axios.post("/Student/delete", qs.stringify({"method": "delete", "id": id})).then(function (result) {
                    if (result.data.code === 2000) {
                        that.tableData = result.data.data;
                        that.initTable();
                    }
                })

            },
            //添加的点击事件
            addStu(){
                this.$refs['addRuleForm'].validate((valid) => {
                    if (valid) { //表单校验通过
                        var qs=Qs;
                        var that=this;
                        axios.post("/Student/insert",qs.stringify(this.addform)).then(function(result){
                            if(result.data.code===2000){
                                that.$message.success(result.data.msg);
                                that.initTable();//重新加载表格
                                that.addform = {};//重置添加表单
                                that.addDialogVisible=false; //隐藏弹出层
                            }
                        })
                    }
                });
            },
            //修改按钮点击事件
            edit(row){
                //显示修改弹出层
                this.editDialogVisible=true;
                //回显数据
                this.editform=row;
            },
            //确认修改
            editStu(){
                var that=this;
                var qs=Qs;
                this.$refs['editRuleForm'].validate((valid) => {
                    if (valid) { //表单校验通过
                        axios.post("/Student/update",qs.stringify(this.editform)).then(function(result){
                            if(result.data.code===2000){
                                that.$message.success(result.data.msg);//弹出成功的消息
                                that.editDialogVisible=false; //隐藏修改对话框
                                that.initTable(); //重新加载表格数据
                            }
                        })
                    }
                });
            },
            //退出
            quit(){
                axios.post("/user/quit").then(function (result){
                    location.href = "login.jsp"
                })
            }
        }
    })
</script>
</html>

4.添加

service层

//添加
    public CommonResult add(Student s) {
        int i = sm.insert(s);
        return new CommonResult(2000,"添加成功",null);
    }

controller操作层:

//添加
    @RequestMapping("insert")
    public CommonResult insert(Student s){
        CommonResult add = ss.add(s);
        return add;
    }

 5.修改

service层

//修改
    public CommonResult upd(Student s) {
        int i = sm.updateByPrimaryKey(s);
        return new CommonResult(2000,"修改成功",null);
    }

controller操作层:

//修改
    @RequestMapping("update")
    public CommonResult update(Student s){
        CommonResult upd = ss.upd(s);
        return upd;
    }

6.删除

service层

//删除
    public CommonResult del(Integer id) {
        int i = sm.deleteByPrimaryKey(id);
        return new CommonResult(2000,"删除成功",null);
    }

controller操作层:

//删除
    @RequestMapping("delete")
    public CommonResult delete(Integer id){
        CommonResult del = ss.del(id);
        return del;
    }