搭建简易的ssmp项目

创建一个SpringBoot工程,勾选web以及mysql驱动,创建完成后在依赖中添加三个起步依赖Lombok mybatis plus druid(其实有四个,上述勾选的web以及mysql以及自动帮我们配置后起步依赖了)

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.6</version>
        </dependency>
 

添加完成起步依赖后,我们配置一下端口号,以及mybatis plus的相关数据,设置端口为80端口,配置druid的数据,添加上对应的本地数据库数据,因为本地的数据表名为tbl_book所以在配置的时候添加了一个前缀,并且id设置为自动,不设置自动则会变为默认的算法来设置id在最后添加日志,能够在控制台观察sql语句以及相关操作。

server:
  port: 80

spring:
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/db1?serverTimezone=UTC
      username: root
      password: 123456
mybatis-plus:
  global-config:
    db-config:
      table-prefix: tbl_
      id-type: auto
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

创建book实体类使用Lombok来自动装配get set等方法注:一定要在类名上配置@Data让spring扫描到

@Data
public class Book {
    private Integer id;
    private String type;
    private String name;
    private String description;
}

使用mybatis plus来创建dao层只要创建一个接口再继承BaseMapper<这里添加对应的实体类也就是这个项目的Book类>注:一定要在类名上配置@Mapper让spring扫描到

@Mapper
public interface BookDao  extends BaseMapper<Book> {

}

创建Service接口,再次使用mybatis plus中的方法,使得创建的Service接口继承IService<Book>来自动装配好了增删改查等大量的方法,也可以在上面再次自己定义自己的方法。

public interface IBookService extends IService<Book> {
    

}

再在Service层中添加impl文件在文件中创建IBookServiceImpl来实现IBookService接口,在其中继承ServiceImpl<BookDao,Book>来实现IService装配的方法,并且实现IBookService接口注:一定要在类名上配置@Service让spring扫描到

@Service
public class IBookServiceImpl extends ServiceImpl<BookDao, Book> implements IBookService {

}

在次之前先设置好前端的相关页面代码,这里直接复制了黑马课程中给的前端代码。

创建统一的后端返回格式,是的前端接收到的数据格式统一,创建返回类R来将返回数据进行统一封装用mybatis plus中的@Data来自动装配方法。

@Data
public class R {
    private Boolean flag;
    private Object data;
    private String msg;
    public R(){}

    public R(Boolean flag){
        this.flag=flag;
    }

    public R(Boolean flag,Object data){
        this.flag =flag;
        this.data= data;
    }

    public R(Boolean flag,String msg){
        this.flag =flag;
        this.msg = msg;
    }

    public R(String msg){
        this.flag =false;
        this.msg = msg;
    }
}

创造不同的带参方法接收不同状态下的数据。

创建controller层,创建BookController,自动装配IBookService接口,并且在里面调用接口中的方法,返回统一用上述的R对象封装类名上添加@RestController来让spring知道是rest风格,@RequestMapping("/books")定位地址是/books里的方法。

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private IBookService bookService;

}

添加getAll方法,来查询所有的数据使用@GetMapping,在输入正确的地址并且用get方式获取则会走getAll方法调用bookService里的方法查询所有数据。

@GetMapping
    public R getAll(){
        System.out.println("getAll begin");
        return new R(true,bookService.list());
    }

前端使用的element+vue搭建的,vue挂载定义各种初始的数据:

 var vue = new Vue({
    el: '#app',
    data: {
        dataList: [],
        dialogFormVisible: false,
        dialogFormVisible4Edit: false,
        formData: {},
        rules: {
            type: [{required: true, message: '图书类别为必填项', trigger: 'blur'}],
            name: [{required: true, message: '图书名称为必填项', trigger: 'blur'}]
        },
        pagination: {
            currentPage: 1,
            pageSize: 10,
            total: 0,
            type: "",
            name: "",
            description: ""
        }
    },

创建初始网页刷新的时候自动调用的方法,使得网页在打开的时候自动调用获取数据(getAll)的方法:

created() {
        this.getAll();
    },

并且在前端接受后端传过来的数据,显示在网页上:

<el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>
                <el-table-column type="index" align="center" label="序号"></el-table-column>
                <el-table-column prop="type" label="图书类别" align="center"></el-table-column>
                <el-table-column prop="name" label="图书名称" align="center"></el-table-column>
                <el-table-column prop="description" label="描述" align="center"></el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
                        <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>

获取后端传过来的datalist并且读取里面的数据显示在网页上:

 因为添加了日志效果,在控制台能看到sql语句以及查询到的数据:

 在Controller层添加新建方法,rest风格使用post方法才能调用save方法,因为后端接受到前端发来的是json数据,所以在Book封装的前面加上@RequestBody来获取:

@PostMapping
    public R save(@RequestBody Book book) throws IOException {
        if (book.getName().equals("123")) throw new IOException();
        boolean flag = bookService.save(book);
        return new R(flag,flag ?"添加成功^_^":"添加失败-_-!");
    }

因为默认新建窗口是隐藏状态,在单击新建的时候我们需要显示新建界面,所以我们在单击新建的时候添加handleCreate方法,使得dialogFormVisible数据改为true来显示新建界面:

handleCreate() {
            this.dialogFormVisible = true;
        },

测试是否成功:

 再次单击确定键应该调用Controller的save方法,将数据储存在数据库内,所以在确定按钮上添加单击事件handleAdd,使用axios方法异步刷新,post方法,并且传绑定的formData数据给后端,判断后端返回值是否为true如果为true则将新建界面显示数据该成false隐藏界面,并且网页显示弹出成功数据,与用户有一定的交互,否则则返回失败信息,事件完成的最后再调用getAll方法,重新更新表中的数据刷新在页面上给用户:

handleAdd() {
            axios.post("/books", this.formData).then((res) => {
                if (res.data.flag) {
                    this.dialogFormVisible = false;
                    this.$message.success(res.data.msg);
                } else {
                    this.$message.error(res.data.msg);

                }
            }).finally(() => {
                this.getAll();
            });

这里会有一个小地方需要修改,因为在调用新建界面的时候存储完一个数据,再次新建的时候,新建界面有上一次提交的数据,这样影响用户体验,我们要在每次调用新建界面的时候,将之前的数据给清空,这时候就要再添加一个方法resetFrom来清空表单数据:

resetForm() {
            this.formData = {};
        },

再在每次打开新建界面的方法里添加调用这个方法:

handleCreate() {
            this.dialogFormVisible = true;
            this.resetForm();
        },

这样就解决了上述的问题。

再在Controller层中添加更新方法,更新方法跟储存方法差不多,增加获取数据以及修改数据的步骤即可添加UpdateById方法。

@PutMapping
    public R UpdateById(@RequestBody Book book){
        return new R(bookService.updateById(book));

    }

调用boolService中mybatis plus自动装配的updayeById方法,将book数据传进去。

前端则需要在getAll方法查询的每条数据后面的编辑按钮上添加事件handleUpdate(scope.row),这个方法传递了一个数据给方法,这个数据就是该条数据的id属性,这样就能精准定位到要修改的数据。

handleUpdate(row) {
            axios.get("/books/" + row.id).then(res => {
                if (res.data.flag && res.data.data != null) {
                    this.dialogFormVisible4Edit = true;
                    this.formData = res.data.data;
                } else {
                    this.$message.error(res.data.msg);
                }
            }).finally(() => {
                this.getAll();
            });

使用阿贾克斯的get方法,并且在路径上调用上述方法传递过来的id使得定位到数据,单击时候改变修改窗口状态为true显示状态,将查询到的数据赋值给formData回显在修改页面上。

当回显数据完成,用户就能在修改页面进行修改相关的操作,在修改成功后,点击确认再调用handleEdit方法将修改表单里的数据以json传给后端,并且将修改界面的显示状态修改为false隐藏起来,成功则返回成功的信息,最后再调用getAll来查询更新后的数据显示在网页上。

handleEdit() {
            axios.put("/books", this.formData).then(res => {
                if (res.data.flag) {
                    this.dialogFormVisible4Edit = false;
                    this.$message.success(res.data.msg);
                } else {
                    this.$message.error(res.data.msg);
                }
            }).finally(() => {
                this.getAll();
            });
        },
    }

做完修改按钮就要做一下旁边的删除按钮handleDelete(scope.row)方法,跟修改差不多,也是获取了该数据的id传给后端,删除对应的数据并且调用getAll方法来刷新数据:

handleDelete(row) {
            this.$confirm("删除的数据将不可恢复,是否继续?", "提示", {type: "info"}).then(() => {
                axios.delete("/books/" + row.id).then(res => {
                    if (res.data.flag) {
                        this.$message.success("删除成功");
                    } else {
                        this.$message.error("删除失败");
                    }
                }).finally(() => {
                    this.getAll();
                });
            }).catch(() => {
                this.$message.info("取消操作");
            });
        },

在删除操作前,应当询问用户是否确认删除,只有等到确认了才能进行删除操作,将id传到后端删除操作,删除成功弹出删除成功提示,否则弹出删除失败,在删除后也要再次调用getAll方法来刷新数据。

 这样上述的增删改查就都做好了,其实在这里我已经提前将分页做完成了,在前端getAll里可以体现:

getAll() {
            //组织参数,拼接url请求地址
            axios.get("/books/" + this.pagination.currentPage + "/" + this.pagination.pageSize+param).then((res) => {
                this.pagination.pageSize = res.data.data.size;
                this.pagination.currentPage = res.data.data.current;
                this.pagination.total = res.data.data.total;
                this.dataList = res.data.data.records;
            });
        },

在这代码中,我们获取了表单里面的默认数据pagination.currentPage pagination.pageSize中的数据以10条数据每页来进行分页,注意这里的分页是完不成的,在测试的时候发现sql语句里没有limit,要再添加一个拦截器才能使用,我们添加一个mybatis plus专用的拦截器,拦截分页功能并且让spring扫描到:

@Configuration
public class MPConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor  interceptor = new MybatisPlusInterceptor();
        //分页拦截器
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }

}

这样再次进行分页就能完成分页操作,并将分页的相关参数数据赋值到网页的默认数据中在页面显示。

再次添加一个模糊查询的功能,就在getAll里面添加一个url拼接的请求地址,将模糊查询的数据传输到后端接收:

getAll() {
            //组织参数,拼接url请求地址
            param = "?type=" + this.pagination.type + "&name=" + this.pagination.name + "&description=" + this.pagination.description;
            axios.get("/books/" + this.pagination.currentPage + "/" + this.pagination.pageSize+param).then((res) => {
                this.pagination.pageSize = res.data.data.size;
                this.pagination.currentPage = res.data.data.current;
                this.pagination.total = res.data.data.total;
                this.dataList = res.data.data.records;
            });
        },

再将字符串封装到param中添加到请求路径的后面,让后端的rest风格能接收并且查询成功相关数据显示在网页上,单击查询按钮就等于传数据到后端并且再次进行getAll操作刷新数据:

 

 查询功能测试成功,这个项目搭建还是有很多小bug需要修复,后期有机会可以回来将网页的一些功能bug进行修复。

总结:

通过这次的smmp项目的搭建,能够使得前后端交互的操作及其流程更加清晰,能够自己简单的搭建一个小项目。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值