[SSM]前后台协议联调①

导读:本篇文章讲解 [SSM]前后台协议联调①,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

也许你感觉自己的努力总是徒劳无功,但不必怀疑,你每天都离顶点更进一步。今天的你离顶点还遥遥无期。但你通过今天的努力,积蓄了明天勇攀高峰的力量。加油!

前后台协议联调

环境准备

项目结构与前文相同:
在这里插入图片描述
我们添加新的静态资源:
在这里插入图片描述
因为添加了静态资源,SpringMVC会拦截,所有需要在SpringConfig的配置类中将静态资源进行放行:

我们新建SpringMvcSupport

@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
        registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
    }
}

配置完成后,我们要在SpringMvcConfig中扫描SpringMvcSupport:

@Configuration
@ComponentScan({"com.nefu.controller","com.nefu.config"})
@EnableWebMvc
public class SpringMvcConfig {
}

接下来我们就需要将所有的列表查询、新增、修改、删除等功能一个个来实现下。

列表功能

在这里插入图片描述
需求:页面加载完后发送异步请求到后台获取列表数据进行展示。

  1. 找到页面的钩子函数,created()

  2. created()方法中调用了this.getAll()方法

  3. 在getAll()方法中使用axios发送异步请求从后台获取数据

  4. 访问的路径为http://localhost/books

  5. 返回数据

返回数据res.data的内容如下:

{
    "data": [
        {
            "id": 1,
            "type": "计算机理论",
            "name": "Spring实战 第五版",
            "description": "Spring入门经典教程,深入理解Spring原理技术内幕"
        },
        {
            "id": 2,
            "type": "计算机理论",
            "name": "Spring 5核心原理与30个类手写实践",
            "description": "十年沉淀之作,手写Spring精华思想"
        },...
    ],
    "code": 20041,
    "msg": ""
}

发送方式:

getAll() {
    //发送ajax请求
    axios.get("/books").then((res)=>{
        this.dataList = res.data.data;
    });
}

在这里插入图片描述

添加功能

在这里插入图片描述
需求:完成图片的新增功能模块

  1. 找到页面上的新建按钮,按钮上绑定了@click="handleCreate()"方法

  2. 在method中找到handleCreate方法,方法中打开新增面板

  3. 新增面板中找到确定按钮,按钮上绑定了@click="handleAdd()"方法

  4. 在method中找到handleAdd方法

  5. 在方法中发送请求和数据,响应成功后将新增面板关闭并重新查询数据

handleCreate打开新增面板

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

handleAdd方法发送异步请求并携带数据

handleAdd () {
    //发送ajax请求
    //this.formData是表单中的数据,最后是一个json数据
    axios.post("/books",this.formData).then((res)=>{
        this.dialogFormVisible = false;
        this.getAll();
    });
}

添加功能状态处理

基础的新增功能已经完成,但是还有一些问题需要解决下:

需求:新增成功是关闭面板,重新查询数据,那么新增失败以后该如何处理?

1.在handlerAdd方法中根据后台返回的数据来进行不同的处理

2.如果后台返回的是成功,则提示成功信息,并关闭面板

3.如果后台返回的是失败,则提示错误信息

(1)修改前端页面

handleAdd () {
    //发送ajax请求
    axios.post("/books",this.formData).then((res)=>{
        //如果操作成功,关闭弹层,显示数据
        if(res.data.code == 20011){
            this.dialogFormVisible = false;
            this.$message.success("添加成功");
        }else if(res.data.code == 20010){
            this.$message.error("添加失败");
        }else{
            this.$message.error(res.data.msg);
        }
    }).finally(()=>{
        this.getAll();
    });
}

(2)后台返回操作结果,将Dao层的增删改方法返回值从void改成int

public interface BookDao {

//    @Insert("insert into tbl_book values(null,#{type},#{name},#{description})")
    @Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})")
    public int save(Book book);

    @Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")
    public int update(Book book);

    @Delete("delete from tbl_book where id = #{id}")
    public int delete(Integer id);

    @Select("select * from tbl_book where id = #{id}")
    public Book getById(Integer id);

    @Select("select * from tbl_book")
    public List<Book> getAll();
}

(3)在BookServiceImpl中,增删改方法根据DAO的返回值来决定返回true/false

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;

    public boolean save(Book book) {
        return bookDao.save(book) > 0;
    }

    public boolean update(Book book) {
        return bookDao.update(book) > 0;
    }

    public boolean delete(Integer id) {
        return bookDao.delete(id) > 0;
    }

    public Book getById(Integer id) {
        if(id == 1){
            throw new BusinessException(Code.BUSINESS_ERR,"请不要使用你的技术挑战我的耐性!");
        }
//        //将可能出现的异常进行包装,转换成自定义异常
//        try{
//            int i = 1/0;
//        }catch (Exception e){
//            throw new SystemException(Code.SYSTEM_TIMEOUT_ERR,"服务器访问超时,请重试!",e);
//        }
        return bookDao.getById(id);
    }

    public List<Book> getAll() {
        return bookDao.getAll();
    }
}

(4)测试错误情况,将图书类别长度设置超出范围即可

在这里插入图片描述
处理完新增后,会发现新增还存在一个问题,

新增成功后,再次点击新增按钮会发现之前的数据还存在,这个时候就需要在新增的时候将表单内容清空。

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/122058.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!