当前位置: 首页 > article >正文

springboot创建web项目

一、创建项目

二、导入依赖(pom.xml)

<?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 http://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>2.2.12.RELEASE</version>
    </parent>

    <groupId>com.cy</groupId>
    <artifactId>Springboot-day01-re</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!--②、引入依赖(起步依赖)-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!--mybatis提供依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>

        <!--连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.16</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

</project>

三、配置文件

application.yml文件

server:
  port: 8080
  servlet:
    context-path: /suv
#Spring配置
spring:
  #资源配置
  datasource:
    #数据源类型
    type: com.alibaba.druid.pool.DruidDataSource
    #地址
    url: jdbc:mysql://localhost:3306/rbac
    #用户名
    username: root
    #密码
    password: chenying
    #驱动名称
    driver-class-name: com.mysql.jdbc.Driver
    
#持久层框架配置    
mybatis:
  #别名配置
  type-aliases-package: com.cy.pojo.entity
  #映射文件
  mapper-locations: classpath*:mappers/**/*mapper.xml
  

# 配置日志
logging:
  level:
    root: info
    com.cy: debug

四、XxxApplication内容

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

五、使用注解或config配置文件解决注解问题

package com.cy.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*");
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

六、完成后端的增删查改操作

controller(控制器层)

package com.cy.controller;

import com.cy.pojo.dto.EmployeeDto;

import com.cy.pojo.entity.Employee;
import com.cy.pojo.vo.Result;
import com.cy.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("list")
//解决跨域问题
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @GetMapping("/{pageNo}/{pageSize}")
    public Result queryPage(@PathVariable("pageNo") Integer pageNo,
                            @PathVariable("pageSize") Integer pagesize,
                            @RequestParam(required = false) String  username ){
     EmployeeDto employees= employeeService.PageByData(pageNo,pagesize,username);
        Result result = Result.builder()
                .code(20000)
                .message("查询成功")
                .data(employees)
                .build();
        return result;
    }

    @PostMapping("/save")
    public Result save(@RequestBody Employee employee){
       Integer add= employeeService.addByData(employee);
       if (add==null){
           return Result.builder().code(50000).message("新增失败").build();
       }
        return  Result.builder().code(20000).message("新增成功").build();
    }

    @RequestMapping("/listById")
    public Result getById(@RequestParam("id") Integer id){
        Employee employee=employeeService.selectById(id);
        if (employee==null){
            return Result.builder().code(50000).message("查询失败").build();
        }
        return   Result.builder()
                .code(20000)
                .message("查询成功")
                .data(employee)
                .build();
    }

    @PutMapping("/update")
    public Result update(@RequestBody Employee employee){
        Integer update=employeeService.updateByData(employee);
        if (update==null){
            return Result.builder().code(50000).message("修改失败").build();
        }
        return  Result.builder().code(20000).message("修改成功").build();
    }

    @DeleteMapping("/delete")
    public Result del(@RequestParam Integer id){
        Integer del=employeeService.delById(id);
        if (del==null){
            return Result.builder().code(50000).message("删除失败").build();
        }
        return  Result.builder().code(20000).message("删除成功").build();
    }

    @RequestMapping("/batchDel")
    public Result batchDel(@RequestBody List<Integer> ids){
        Integer dels= employeeService.batchDel(ids);
        if (dels==null){
            return Result.builder().code(50000).message("批量删除失败").build();
        }
        return  Result.builder().code(20000).message("批量删除成功").build();
    }

}

service(业务逻辑层)

package com.cy.service;

import com.cy.pojo.dto.EmployeeDto;
import com.cy.pojo.entity.Employee;

import java.util.List;

public interface EmployeeService {
    EmployeeDto PageByData(Integer pageNo, Integer pagesize, String username);

    Integer addByData(Employee employee);

    Integer updateByData(Employee employee);

    Employee selectById(Integer id);

    Integer delById(Integer id);

    Integer batchDel(List<Integer> ids);
}
package com.cy.service.impl;

import com.cy.mapper.EmployeeMapper;
import com.cy.pojo.dto.EmployeeDto;
import com.cy.pojo.entity.Employee;
import com.cy.service.EmployeeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Resource
    private EmployeeMapper employeeMapper;
    @Override
    public EmployeeDto PageByData(Integer pageNo, Integer pagesize,String username) {
        Integer total=employeeMapper.sum();

        int ceil =(int) Math.ceil((total / (double) pagesize));
        Integer c=ceil;
        Integer start;
        if (pageNo<c){
            start=(pageNo-1)*pagesize;
        }else {
            start=(ceil-1)*pagesize;
        }
        List<Employee> employeeList=employeeMapper.getPage(start,pagesize,username);

        EmployeeDto dto = EmployeeDto.builder()
                .pageNo(pageNo)
                .pageSize(pagesize)
                .total(ceil)
                .dataList(employeeList)
                .build();

        return dto;
    }

    @Override
    public Integer addByData(Employee employee) {
        Integer add=employeeMapper.add(employee);

        return add;
    }

    @Override
    public Integer updateByData(Employee employee) {
        Integer update=employeeMapper.updateByData(employee);

        return update;
    }

    @Override
    public Employee selectById(Integer id) {
        Employee employee=employeeMapper.getById(id);

        return employee;
    }

    @Override
    public Integer delById(Integer id) {
        Integer del=employeeMapper.del(id);

        return del;
    }

    @Override
    public Integer batchDel(List<Integer> ids) {
        return employeeMapper.batchDel(ids);
    }
}

mapper(数据访问层)

package com.cy.mapper;

import com.cy.pojo.entity.Employee;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

@Mapper
public interface EmployeeMapper {
    List<Employee> getPage(@Param("start") Integer start,
                           @Param("pageSize") Integer pagesize,
                           @Param("username") String username);

    Integer sum();

    Integer add(Employee employee);

    Integer updateByData(Employee employee);

    Employee getById(Integer id);

    Integer del(Integer id);

    Integer batchDel(List<Integer> ids);
}

mappers

<?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.cy.mapper.EmployeeMapper">
    <insert id="add">
        insert into employee(username,name,password,email,age,admin,dept_id)
                values(#{username},#{name},#{password},#{email},#{age},#{admin},#{deptId})
    </insert>
    <update id="updateByData">
        update employee
            <set>
                <if test="username!=null">
                    username=#{username},
                </if>
                <if test="name!=null">
                    name=#{name},
                </if>
                <if test="password!=null">
                    password=#{password},
                </if>
                <if test="email!=null">
                    email=#{email},
                </if>
                <if test="age!=null">
                    age=#{age},
                </if>
                <if test="admin!=null">
                    admin=#{admin},
                </if>
                <if test="deptId!=null">
                    dept_id=#{deptId},
                </if>
            </set>
            where id=#{id}

    </update>
    <delete id="del">
        delete from employee where id=#{id}
    </delete>
    <delete id="batchDel">
        delete from employee
            where id
            <trim prefix="in (" suffix=")" suffixOverrides=",">
            <foreach collection="ids" item="item" separator=",">
                #{item}
            </foreach>
            </trim>
    </delete>
    <!--<mapper namespace="">-->


    <select id="getPage" resultType="com.cy.pojo.entity.Employee">
        select * from employee
            <where>
                <if test="username!=null">
                   and username like concat("%",#{username},"%")
                </if>
            </where>
            <if test="start!=null and pageSize!=null">
                limit #{start},#{pageSize}
            </if>
    </select>
    <select id="sum" resultType="java.lang.Integer">
        select count(*) from employee
    </select>
    <select id="getById" resultType="com.cy.pojo.entity.Employee">
        select * from employee
            where id=#{id}
    </select>
</mapper>

还有一些简单的工具类

EmployeeDto

package com.cy.pojo.dto;

import com.cy.pojo.entity.Employee;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author chen
 * @Version 1.0
 * @Date 2024/12/24
 * @Description 返回前端的数据
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class EmployeeDto {
    /**
     *数据总数
     */
    private Integer total;

    /**
     *页面数
     */
    private Integer pageNo;

    /**
     *每页数据大小
     */
    private Integer pageSize;

    /**
     *数据集合
     */
    private List<Employee> dataList=new ArrayList<>();
}

实体类

package com.cy.pojo.entity;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
    /**
     *主键
     */
    private Integer id;
    /**
     *用户名
     */
    private String username;
    /**
     *名称
     */
    private String name;
    /**
     *密码
     */
    private String password;
    /**
     *邮箱
     */
    private String email;
    /**
     *年龄
     */
    private Integer age;
    /**
     *管理员
     */
    private Integer admin;
    /**
     *所属部门
     */
    private Integer deptId;

    //角色id集
    //private List<Integer> roleIds = new ArrayList<>();
}

统一后端返回前端的格式

package com.cy.pojo.vo;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @Author chen
 * @Version 1.0
 * @Date 2024/12/24
 * @Description 统一返回类型
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Result {
    /**
     *状态码
     */
    private Integer code;
    /**
     *提示信息
     */
    private String  message;
    /**
     *返回数据
     */
    private Object data;

}

前端HTML页面效果显示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- Bootstrap -->
    <link rel="stylesheet" href="./css/bootstrap.css" >
    <script src="./js/vue.js"></script>
    <script src="./js/axios.min.js"></script>
</head>
<body>
<div id="app">
<table class="table">
    <form class="form-inline">
            <label >产品名/概述</label>
            <input type="text" v-model="username" placeholder="请输入产品名/概述">
        <button type="submit" @click="search">搜索</button>
        <button class="fat-btn"
                type="button" style="background-color: #269abc" @click="resBtn">重置
        </button>
    </form>
    <div>
    <button class="fat-btn"
            type="button" style="background-color: #269abc" @click="asveBtn"> 新增
    </button>
    <button class="fat-btn"
            type="button" style="background-color: tomato" @click="batchDel"> 批量删除
    </button>
    </div>
    <thead>
    <tr>
        <th>选择</th>
        <th>用户名</th>
        <th>用户</th>
        <th>密码</th>
        <th>邮件</th>
        <th>年龄</th>
        <th>管理员</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <tr v-for="(value,key) in dataList" :key="key">
        <td>
            <input type="checkbox" :value="value.id" v-model="ids">
        </td>
        <td>{{value.username}}</td>
        <td>{{value.name}}</td>
        <td>{{value.password}}</td>
        <td>{{value.email}}</td>
        <td>{{value.age}}</td>
        <td>{{value.admin}}</td>
         <td>
             <button
                     type="button" style="background-color: tomato" @click="delData(value.id)"> 删除
             </button>
             <button class="fat-btn"
                     type="button" style="background-color: darkcyan" @click="findData(value.id)"> 编辑
             </button>
         </td>
    </tr>
    </tbody>
</table>
    <!--分页-->
    <div style="padding-right: 20px">
    <ul class="pagination" >
        <li><a href="#">&laquo;</a></li>
        <li v-for="page in totalPage" :key="page" >
            <a href="#" :class="{active:page==pageNo}" @click="change(page)">{{page}}</a></li>
        <li><a href="#">&raquo;</a></li>
    </ul>
    </div>
<!--新增窗口-->
     <div style="width: 50%;align-content: center" v-if="newBtn">
    <form>
        <div class="form-group">
            <label >用户名</label>
            <input type="text" class="form-control" v-model="addem.username"  placeholder="用户名">
        </div>
        <div class="form-group">
            <label >用户</label>
            <input type="text" class="form-control" v-model="addem.name"  placeholder="用户">
        </div>
        <div class="form-group">
            <label >密码</label>
            <input type="text" class="form-control" v-model="addem.password" placeholder="密码">
        </div>
        <div class="form-group">
            <label >邮件</label>
            <input type="text" class="form-control" placeholder="邮件" v-model="addem.email">
        </div>
        <div class="form-group">
            <label >年龄</label>
            <input type="text" class="form-control" placeholder="年龄" v-model="addem.age">
        </div>
        <div class="form-group">
            <label >管理员</label>
            <input type="text" class="form-control" placeholder="管理员" v-model="addem.admin">
        </div>
        <div class="form-group">
            <label >所属部门</label>
            <input type="text" class="form-control" placeholder="所属部门" v-model="addem.deptId">
        </div>

        <button type="submit" class="btn btn-default" @click="saveData">确定</button>
        <button type="submit" class="btn btn-default" @click="closeBtn">取消</button>
    </form>
     </div>
<!--编辑窗口-->
    <div  style="width: 50%;align-content: center" v-if="updateBtn">
        <form>
            <div class="form-group">
                <label >用户名</label>
                <input type="text" class="form-control" v-model="empol.username"  placeholder="用户名">
            </div>
            <div class="form-group">
                <label >用户</label>
                <input type="text" class="form-control" v-model="empol.name"  placeholder="用户">
            </div>
            <div class="form-group">
                <label >密码</label>
                <input type="text" class="form-control" v-model="empol.password" placeholder="密码">
            </div>
            <div class="form-group">
                <label >邮件</label>
                <input type="text" class="form-control" placeholder="邮件" v-model="empol.email">
            </div>
            <div class="form-group">
                <label >年龄</label>
                <input type="text" class="form-control" placeholder="年龄" v-model="empol.age">
            </div>
            <div class="form-group">
                <label >管理员</label>
                <input type="text" class="form-control" placeholder="管理员" v-model="empol.admin">
            </div>
            <div class="form-group">
                <label >所属部门</label>
                <input type="text" class="form-control" placeholder="所属部门" v-model="empol.deptId">
            </div>

            <button type="submit" class="btn btn-default" @click="updateData">确定</button>
            <button type="submit" class="btn btn-default" @click="closeBtn">取消</button>
        </form>
    </div>
</div>
    <script src="./js/bootstrap.js"></script>
<script>
    new Vue({
        el:'#app',
        data:{
            pageNo:1,
            pageSize:3,
            totalPage:1,
            dataList:[],
            ids:[],
           username:null,
            form:{
              username:null,
                name:null
            },
            addem:{

            },
            empol:{},
            newBtn:false,
            updateBtn:false
        },
        methods:{
            getAll(){
                console.log("username:",this.username)
                axios({
                    method:'get',
                    url:`http://localhost:8080/suv/list/${this.pageNo}/${this.pageSize}`,
                    params:{
                     username:this.username
                    }
                }).then(resp=>{
                console.log("分页查询的数据:",resp.data)
                    if (resp.data.code===20000){
                        this.dataList=resp.data.data.dataList
                        this.totalPage=resp.data.data.total
                    }

                })
            },
            change(page){
                this.pageNo=page
                this.getAll()
            }
            ,
            /*新增*/
            saveData(){
                axios({
                    method: 'post',
                    url: 'http://localhost:8080/suv/list/save',
                    data: this.addem
                }).then(resp=>{
                    if (resp.data.code===20000){
                        alert(resp.data.message)
                    }else {
                        alert(resp.data.message)
                    }
                })
            },
            findData(id){
                this.updateBtn = true
                axios({
                    method:'get',
                    url:'http://localhost:8080/suv/list/listById',
                    params: {
                        id:id
                    }
                }).then(resp=>{
                    console.log(resp.data)
                    if (resp.data.code===20000){
                        this.empol=resp.data.data
                    }
                })
            }
            ,
            updateData() {
                axios({
                    method:'put',
                    url:'http://localhost:8080/suv/list/update',
                    data:this.empol
                }).then(resp=>{
                    if (resp.data.code===20000){
                        alert(resp.data.message)
                        this.updateBtn=false
                        this.getAll()
                    }
                })
            }
            ,
            asveBtn(){
                this.newBtn=true
            },
            search(){
                this.pageNo = 1,
                this.getAll()
            }
            ,
            resBtn(){
                this.closeBtn()
                this.username=null
                this.getAll()
            },
            closeBtn(){
                this.newBtn = false,
                this.updateBtn = false
            },
        /*删除*/
            delData(id){
                if (confirm("确定删除吗")){
                    axios({
                        method:'delete',
                        url:'http://localhost:8080/suv/list/delete',
                        params:{
                            id:id
                        }
                    }).then(resp=>{
                        if (resp.data.code===20000){
                            alert(resp.data.message)
                        }else {
                            alert(resp.data.message)
                        }
                        this.pageNo=1
                        this.getAll()
                    })
                }

            },
            /*批量删除*/
            batchDel(){
                axios({
                    method:'post',
                    url:'http://localhost:8080/suv/list/batchDel',
                    data:this.ids
                }).then(resp=>{
                    alert(resp.data.message)
                    this.pageNo=1
                    this.getAll()
                })
            }
        },
        created(){
           this.getAll()
        }
    })

</script>
</body>
</html>

数据库数据设置:

效果展示


http://www.kler.cn/a/450296.html

相关文章:

  • 微调大模型时,如何进行数据预处理? 将<input, output>转换为模型所需的<input_ids, labels, attention_mask>
  • alertmanager告警持久化方案:alertsnitch
  • SQL,生成指定时间间隔内的事件次序号
  • BunkerWeb 开源项目安装与使用教程
  • 《Go 语言变量》
  • 【游戏设计原理】22 - 石头剪刀布
  • 【数据结构练习题】链表与LinkedList
  • 华中电子展(OVC)︱2025 武汉国际半导体产业与电子技术博览会:引领未来“芯”科技
  • AIDD - 人工智能药物设计 - 在 Docker 上创建和运行 PostgreSQL + RDKit 卡带环境
  • Java实现Excel带层级关系的数据导出功能
  • 最新高性能多目标优化算法:多目标麋鹿优化算法(MOEHO)求解TP1-TP10及工程应用---盘式制动器设计,提供完整MATLAB代码
  • List 集合安全操作指南:避免 ConcurrentModificationException 与提升性能
  • 模型高效微调方式
  • Mysql-索引数据结构选择合理性
  • KingbaseES(金仓数据库)入门学习
  • 如何在 Ubuntu 22.04 服务器上安装 Jenkins
  • 【LuaFramework】LuaFramework_UGUI_V2框架学习
  • 精彩回顾|在2024全球智博会 Semantic Kernel 开发者日中国站开启企业全智能化应用场景
  • 【超详细实操内容】django的身份验证系统之用户登录与退出
  • 转型云,转型AI,转型大模型,微软为什么如此人间清醒?
  • iClient3D for Cesium在Vue中快速实现场景卷帘
  • 202411 第十六届蓝桥杯青少组 STEMA 考试真题 汇总
  • JavaScript--WebAPI查缺补漏
  • 绿盟CSSP靶场-挂载虚拟化磁盘
  • Android Bootable Recovery 中的 `freecache.cpp` 文件详解
  • Java成长之路(一)--SpringBoot基础学习--SpringBoot代码测试