springboot3+mybatisplus(5)-backend-mybaitsplus+frontend-router

1.backend


1.1.添加依赖




 

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.5.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>my-project-backend</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>my-project-backend</name>
    <description>my-project-backend</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--    Mybatis-Plus框架    -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
            <version>3.5.7</version>
        </dependency>
        <!--    MySQL驱动    -->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.graalvm.buildtools</groupId>
                <artifactId>native-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

1.2.全局配置



 

spring.application.name=my-project-backend
spring.datasource.url=jdbc:mysql://192.168.9.73:3306/pvfforecast?useSSL=false
spring.datasource.username=root
spring.datasource.password=INT@4001093999
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StudOutImpl
mybatis-plus.mapper-locations=classpath:mapper/*.xml


 

package com.myproject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.myproject.mapper") // 指定Mapper接口所在的包
public class MyProjectBackendApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyProjectBackendApplication.class, args);
    }

}

控制器实现

1.主程序添加mapper扫描:注解 @MapperScan("com.myproject.mapper")
2.mapper处理数据库操作:表名+mapper
   不需要去写实现的内容
3.controller处理浏览器的访问   
4.entity实体类:每个表对应一个类
 

浏览器访问:
https://localhost:8080/login
user:
password:



1.3.通过config实现数据库用户名密码登录






 

1.config中添加 service


//注入2个类 密码在数据库里是加密的,浏览器中不加密的
//admin:123456
//自定义的服务类:myauthorizeService
//
 @Bean
    public AuthenticationManager authenticationManager(HttpSecurity security)  throws Exception{
        return  security
                .userDetailsService(myauthorizeService)
                .getSharedObject(AuthenticationManagerBuilder.class)
                .build();
    }
  @Bean
  public BCryptPasswordEncoder passwordEncoder(){
      return new BCryptPasswordEncoder();
  }



  2.service中添加mapper和entity 用于数据库操作
      MyuserMapper.java
 

@Service
public class MyAuthorizeService implements UserDetailsService {

    @Resource
    MyuserMapper myuserMapper;

    @Override
    public UserDetails loadUserByUsername(String username)   throws UsernameNotFoundException {
            if(username == null)
                throw new UsernameNotFoundException("用户名不能为空");
            Myuser myuser = myuserMapper.getuserbyusername(username);
            if(myuser == null)
                throw new UsernameNotFoundException("用户名或密码错误");
            //User 这是一个库里的类
            return User
                    .withUsername(myuser.getUsername())
                    .password(myuser.getPassword())
                    .roles("user")
                    .build();
    }
}

MyuserMapper.java

package com.myproject.mapper;

import com.myproject.entity.Myuser;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface MyuserMapper {

    @Select("select * from myuser where username = #{username} ")
    Myuser getuserbyusername(String username);
}

Myuser.java

import lombok.Data;

@Data
public class Myuser {
    int id;
    String email;
    String username;
    String password;


}

2.frontend
 

2.1系统搭建


1.package.json

名称
私有
版本
模块化规范
端口:5173-4173

2.index.html 入口文件

2.main.js


 

3.App.vue 3个

添加组件
设计 | Element Plus

npm install vue-axios --save
npm install vue-router
npm install pinia

1.写App.vue

2.写router: index.ts 并暴露出去



3.加载进项目里 main.ts

浏览器插件下载:

修改App.vue
 

验证:
localhost:5173/home



 

2.2 路由及路由器

 

<routerlink>

响应鼠标点击:添加RouterLink 



hash模式

 组件分类 route components



2.3.嵌套路由


 修改index.ts

子集不需要写/

调整样式在

2.4 传参query


: news.vue

             
details.vue

route 获取变量
console.log(‘@’,route);打印变量


内容已传递


上面写法只能传一次。

2.5传参params

这不是子路由,是参数

要去index.ts修改文件

参数任意命名 x y z 

打开浏览器 

第一种字符串


第二种写法 对象写法



1.用name 不能是path




不能传对象和数组

2.6路由的props





1.修改规则


 

details 支持 props

运行后看

引用route变量

2.7路由-编程式导航


 

以下是drf+vue3+element-plus搭建CRUD的案例: 1. 创建Django项目,命名为backend,创建Django APP,命名为api。 2. 在api中创建models.py文件,定义模型: ``` from django.db import models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title ``` 3. 在api中创建serializers.py文件,定义序列化器: ``` from rest_framework import serializers from .models import Book class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = &#39;__all__&#39; ``` 4. 在api中创建views.py文件,定义视图: ``` from rest_framework import viewsets from .models import Book from .serializers import BookSerializer class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer ``` 5. 在backend中配置api的url: ``` from django.urls import path, include from rest_framework import routers from api.views import BookViewSet router = routers.DefaultRouter() router.register(r&#39;books&#39;, BookViewSet) urlpatterns = [ path(&#39;api/&#39;, include(router.urls)), ] ``` 6. 在frontend中创建vue3项目,命名为frontend,安装element-ui和axios: ``` yarn add element-plus axios ``` 7. 在frontend中创建src/api/index.js文件,定义请求: ``` import axios from &#39;axios&#39; const instance = axios.create({ baseURL: &#39;http://localhost:8000/api/&#39;, timeout: 1000, headers: {&#39;Content-Type&#39;: &#39;application/json&#39;} }) export default { getBooks() { return instance.get(&#39;books/&#39;) }, createBook(data) { return instance.post(&#39;books/&#39;, data) }, updateBook(id, data) { return instance.put(`books/${id}/`, data) }, deleteBook(id) { return instance.delete(`books/${id}/`) } } ``` 8. 在frontend中创建src/views/BookList.vue文件,定义书籍列表组件: ``` <template> <el-table :data="books" style="width: 100%"> <el-table-column prop="title" label="书名"></el-table-column> <el-table-column prop="author" label="作者"></el-table-column> <el-table-column prop="price" label="价格"></el-table-column> <el-table-column label="操作"> <template #default="{row}"> <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button> <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button> </template> </el-table-column> </el-table> </template> <script> import api from &#39;@/api&#39; export default { name: &#39;BookList&#39;, data() { return { books: [] } }, async created() { const res = await api.getBooks() this.books = res.data }, methods: { handleEdit(row) { this.$router.push({name: &#39;BookEdit&#39;, params: {id: row.id}}) }, async handleDelete(row) { try { await api.deleteBook(row.id) this.books = this.books.filter(book => book.id !== row.id) this.$message.success(&#39;删除成功&#39;) } catch (error) { this.$message.error(&#39;删除失败&#39;) } } } } </script> ``` 9. 在frontend中创建src/views/BookCreate.vue文件,定义创建书籍组件: ``` <template> <el-form :model="form" :rules="rules" ref="form" label-width="80px"> <el-form-item label="书名" prop="title"> <el-input v-model="form.title"></el-input> </el-form-item> <el-form-item label="作者" prop="author"> <el-input v-model="form.author"></el-input> </el-form-item> <el-form-item label="价格" prop="price"> <el-input v-model="form.price"></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="handleSubmit">创建</el-button> </el-form-item> </el-form> </template> <script> import api from &#39;@/api&#39; export default { name: &#39;BookCreate&#39;, data() { return { form: { title: &#39;&#39;, author: &#39;&#39;, price: &#39;&#39; }, rules: { title: [ {required: true, message: &#39;请输入书名&#39;, trigger: &#39;blur&#39;} ], author: [ {required: true, message: &#39;请输入作者&#39;, trigger: &#39;blur&#39;} ], price: [ {required: true, message: &#39;请输入价格&#39;, trigger: &#39;blur&#39;}, {type: &#39;number&#39;, message: &#39;价格必须为数字&#39;, trigger: &#39;blur&#39;} ] } } }, methods: { async handleSubmit() { try { await this.$refs.form.validate() await api.createBook(this.form) this.$message.success(&#39;创建成功&#39;) this.$router.push({name: &#39;BookList&#39;}) } catch (error) { this.$message.error(&#39;创建失败&#39;) } } } } </script> ``` 10. 在frontend中创建src/views/BookEdit.vue文件,定义编辑书籍组件: ``` <template> <el-form :model="form" :rules="rules" ref="form" label-width="80px"> <el-form-item label="书名" prop="title"> <el-input v-model="form.title"></el-input> </el-form-item> <el-form-item label="作者" prop="author"> <el-input v-model="form.author"></el-input> </el-form-item> <el-form-item label="价格" prop="price"> <el-input v-model="form.price"></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="handleSubmit">保存</el-button> </el-form-item> </el-form> </template> <script> import api from &#39;@/api&#39; export default { name: &#39;BookEdit&#39;, data() { return { id: this.$route.params.id, form: { title: &#39;&#39;, author: &#39;&#39;, price: &#39;&#39; }, rules: { title: [ {required: true, message: &#39;请输入书名&#39;, trigger: &#39;blur&#39;} ], author: [ {required: true, message: &#39;请输入作者&#39;, trigger: &#39;blur&#39;} ], price: [ {required: true, message: &#39;请输入价格&#39;, trigger: &#39;blur&#39;}, {type: &#39;number&#39;, message: &#39;价格必须为数字&#39;, trigger: &#39;blur&#39;} ] } } }, async created() { const res = await api.getBooks() const book = res.data.find(book => book.id == this.id) this.form = book }, methods: { async handleSubmit() { try { await this.$refs.form.validate() await api.updateBook(this.id, this.form) this.$message.success(&#39;保存成功&#39;) this.$router.push({name: &#39;BookList&#39;}) } catch (error) { this.$message.error(&#39;保存失败&#39;) } } } } </script> ``` 11. 在frontend中创建src/router/index.js文件,定义路由: ``` import {createRouter, createWebHistory} from &#39;vue-router&#39; import BookList from &#39;@/views/BookList.vue&#39; import BookCreate from &#39;@/views/BookCreate.vue&#39; import BookEdit from &#39;@/views/BookEdit.vue&#39; const routes = [ {path: &#39;/&#39;, name: &#39;BookList&#39;, component: BookList}, {path: &#39;/create&#39;, name: &#39;BookCreate&#39;, component: BookCreate}, {path: &#39;/edit/:id&#39;, name: &#39;BookEdit&#39;, component: BookEdit}, ] const router = createRouter({ history: createWebHistory(), routes }) export default router ``` 12. 在frontend中创建src/main.js文件,初始化vue3和element-plus: ``` import {createApp} from &#39;vue&#39; import App from &#39;./App.vue&#39; import router from &#39;./router&#39; import ElementPlus from &#39;element-plus&#39; import &#39;element-plus/lib/theme-chalk/index.css&#39; createApp(App).use(router).use(ElementPlus).mount(&#39;#app&#39;) ``` 至此,我们成功地实现了一个简单的CRUD功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值