ajax + vue + springboot + Restful实现前后端分离项目

该项目基于上个创建的Springboot项目:https://blog.csdn.net/bat_xu/article/details/81710785

故不展示项目创建过程。

项目结构:

一、编写实体类Category

Category.class

package com.example.springboot.entity;

public class Category {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

二、DAO

使用的MyBatis,所以这里是Category.xml和CategoeyMapper接口

Category.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.example.springboot.mapper.CategoryMapper">

    <select id="findAll" resultType="Category">
        select * from category
    </select>
    <select id="findById" parameterType="_int" resultType="Category">
        SELECT * FROM category WHERE id=#{id}
    </select>
    <insert id="add" parameterType="Category">
        INSERT INTO category (id,name) VALUES (#{id},#{name})
    </insert>
    <delete id="delete" parameterType="_int">
        DELETE FROM category WHERE id=#{id}
    </delete>
    <update id="update" parameterType="Category">
        UPDATE category SET name=#{name} WHERE id=#{id}
    </update>
</mapper>

CategoryMapper.class

package com.example.springboot.mapper;

import com.example.springboot.entity.Category;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@Mapper
public interface CategoryMapper {
    List<Category> findAll();
    void delete(int id);
    void update(Category category);
    void add(Category category);
    Category findById(int id);
}

三、业务层

CategoryService.class

package com.example.springboot.service;

import com.example.springboot.entity.Category;

import java.util.List;

public interface CategoryService {
    List<Category> findAll();
    void delete(int id);
    void update(Category category);
    void add(Category category);
    Category findById(int id);
}

CategoryServiceImpl.class

package com.example.springboot.service;


import com.example.springboot.entity.Category;
import com.example.springboot.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService{
    @Autowired
    CategoryMapper categoryMapper;

    public List<Category> findAll() {
        return categoryMapper.findAll();
    }
    public void delete(int id) {
        categoryMapper.delete(id);
    }
    public void update(Category category) {
        categoryMapper.update(category);
    }
    public void add(Category category) {
        categoryMapper.add(category);
    }
    public Category findById(int id) {
        return categoryMapper.findById(id);
    }
}

四、控制层

MainController.class

package com.example.springboot.controller;

import com.example.springboot.entity.Category;
import com.example.springboot.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/")
public class MainController {
    @Autowired
    CategoryService categoryService;

    //获取
    @GetMapping("/category")
    public List<Category> list() {
        List<Category> categories = categoryService.findAll();
        return categories;
    }

    //获取
    @GetMapping("/category/{id}")
    public Category getCategory(@PathVariable("id") int id) {
        Category category = categoryService.findById(id);
        return category;
    }

    //删除
    @DeleteMapping("/category/{id}")
    public String deleteCategory(@PathVariable("id") int id) {
        categoryService.delete(id);
        return "true";
    }

    //添加
    @PutMapping("/category")
    public String addCategory(Category category) {
        categoryService.add(category);
        return "true";
    }

    //修改
    @PostMapping("/category/{id}")
    public String updateCategory(@PathVariable("id") int id, Category category) {
        Category category1 = categoryService.findById(id);
        category1.setName(category.getName());
        categoryService.update(category1);
        return "true";
    }
}

Springboot实现Restful很简单:
1.用@RestController注解取代@Controller注解,作用是默认将所有方法标识@ResponseBody注解返回json数据给前端。(Springboot的web starter已经集成了json的相关包无用额外添加依赖)
2.用@GetMapping,@DeleteMapping,@PutMapping和@PostMapping取代了@RequestMapping相当于增加了method=“GET”等,根据请求方法映射到不同的方法。这就是Restful的核心思路

五、前端页面

listCategory.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>List</title>
    <script src="http://how2j.cn/study/vue.min.js"></script>
    <script src="http://how2j.cn/study/jquery.min.js"></script>
    <script>
        $(function () {
            var page = "/category";
            // 从后台获取数据
            getCategory(page);
        })
        function getCategory(page) {
            // 使用ajax发起一个GET方法的请求
            $.get(
                page,
                // result参数是后台传过来的category数组
                function (result) {
                    // 将返回结果绑定到UI上,这里用到了vue
                    new Vue({
                        el:'#div1',
                        data:{
                            categories:result,
                        }
                    })
                }
            )
        }
        function add() {
            var page = "/category";
            $.ajax({
                url:page,
                type:"put", // 使用的put方法,对应后台中的添加方法
                datatype:"json",
                data:$("#addForm").serialize(),
                success:function () {
                    location.reload()
                }
            })
        }
    </script>
</head>
<body>
<div id="div1" style="width:500px;margin:20px auto;text-align: center">
    <table align='center' border='1' cellspacing='0'>
        <tr>
            <td>id</td>
            <td>name</td>
            <td>编辑</td>
            <td>删除</td>
        </tr>
        <!-- 这里利用的Vue的循环,绑定数据到UI上非常方便,而且代码可读性好-->
        <tr v-for="category in categories">
            <td>{{category.id}}</td>
            <td>{{category.name}}</td>
            <td><a href="">编辑</a></td>
            <td><a class="delete" href="#">删除</a></td>
        </tr>

    </table>
    <br>
    <br>
    <form id="addForm" action="" method="">
        name: <input id="name" name="name"> <br>
    </form>
    <button id="addCategory" type="button" onclick="add()">提交</button>
</div>

</body>
</html>

这里是使用的html文件使用ajax进行前后端的交互,实现了前后端分离。

重点是ajax的几个请求调用Restful风格的API向后台获取数据,然后绑定数据使用了Vue,比js直接控制dom更为方便。

最后配置文件和pom.xml的依赖在开头中创建项目的博客中已经写出。

六、整理思路

首先打开http://localhosts:8080/springboot/listCategory.html

页面加载后如js代码写到的,将发送.get的ajax请求,向后台获取到category列表,然后通过Vue渲染到div中显示出来。

后台获取请求根据url和GET映射到list()方法,该方法将从数据库取出category列表,转换成json(通过@ResponseBody注解快速实现)数据发给前端。

猜你喜欢

转载自blog.csdn.net/bat_xu/article/details/82597149
今日推荐