使用SpringBoot框架搭建简易的项目

一.项目搭建及基础配置

1.1 Spring Boot 项目创建

核心概念

Spring Boot = 简化 Spring 开发的框架

自动配置 + 起步依赖

核心知识点

SpringBoot优势:快速开发,简化配置,内嵌服务器

项目结构

src/main/java - Java 源代码

src/main/resources - 配置文件

src/test/java - 测试代码

pom.xml - Maven 依赖管理

1.2 Maven 依赖管理

复制代码
<!--依赖的父级工程-->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.6</version>
    <relativePath/>
</parent>
复制代码
<!--添加基本的 springweb 依赖-->
    <dependencies>
<!--    web    -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<!--    jdbc    -->
        <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.1.4</version>
        </dependency>
        <!--    jwt的依赖    -->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.8.2</version>
        </dependency>
        <!--mysql jar的坐标-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

1.3 配置文件 application.yml

server:

port: 8080

spring:

datasource:

driver-class-name: com.mysql.jdbc.Driver

url: jdbc:mysql://localhost:3306/newsdb?useUnicode=true&characterEncoding=utf8&useSSL=false

username: root

password: root

mybatis:

type-aliases-package: com.ljl.news.model

mapper-locations: classpath:mappers/*Mapper.xml

configuration:

map-underscore-to-camel-case: true

  • **YAML 格式 :缩进敏感、层级清晰
  • 数据源配置 :驱动类、URL、用户名、密码
  • MyBatis 配置 :
  • type-aliases-package :实体类别名包
  • mapper-locations :Mapper XML 文件位置
  • map-underscore-to-camel-case :下划线转驼峰**

第二阶段:后端核心开发

2.1 分层架构设计

经典三层架构

Controller 控制层

Service 业务层

Dao/Repository 数据访问层

Database 数据库

各自职责:

  • Controller :接收请求、返回响应

  • Service :业务逻辑处理、事务管理

  • Dao :数据库操作(SQL)

2.2 实体类(Model)

Admin.java 示例

@Component
@Scope(value = "prototype")
public class Admin {
private int id;
private String account;
private String password;
private int type;
private String gender;
private String phone;
private Date operTime;
// Getter 和 Setter
}

**- 注解 :

  • @Component :Spring 管理的 Bean
  • @Scope("prototype") :多例模式
  • 字段映射 :数据库字段 ↔ Java 属性**

2.3 数据访问层(Dao/Mapper)

AdminDao.java 接口

@Mapper
public interface AdminDao {
ArrayList<Admin> admins();
ArrayList<Admin> getAdminList(@Param("account") String account,
@Param("type") String type,
@Param("offset") int offset,
@Param("size") int size);
int getAdminCount(@Param("account") String account, @Param("type") String type);
void add(Admin admin);
void update(Admin admin);
void delete(int id);
}

**- @Mapper 注解 :MyBatis 识别的 Mapper 接口

  • @Param 注解 :参数命名,用于 XML 中引用
  • 方法签名 :与 XML 中的 SQL 语句对应**

2.4 MyBatis Mapper XML

AdminMapper.xml 示例

<mapper namespace="com.ljl.news.dao.AdminDao">
<!-- 查询列表 -->
<select id="getAdminList" resultType="com.ljl.news.model.Admin">
select id, account, password, type, gender, phone, oper_time as operTime
from admin
<where>
<if test="account != null and account != ''">
and account like concat('%', #{account}, '%')
</if>
<if test="type != null and type != ''">
and type = #{type}
</if>
</where>
order by id desc
limit #{offset}, #{size}
</select>
<!-- 插入 -->
<insert id="add" parameterType="com.ljl.news.model.Admin" useGeneratedKeys="true" keyProperty="id">
insert into admin (account, password, type, gender, phone, oper_time)
values (#{account}, #{password}, #{type}, #{gender}, #{phone}, #{operTime})
</insert>
<!-- 更新 -->
<update id="update" parameterType="com.ljl.news.model.Admin">
update admin
set account = #{account},
<if test="password != null and password != ''">
password = #{password},
</if>
type = #{type},
gender = #{gender},
phone = #{phone},
oper_time = #{operTime}
where id = #{id}
</update>
<!-- 删除 -->
<delete id="delete" parameterType="int">
delete from admin where id = #{id}
</delete>
</mapper>

**- namespace :绑定对应的 Dao 接口

  • 动态 SQL :
  • <where> :自动处理 AND/OR
  • <if> :条件判断
  • concat() :字符串拼接
  • 参数引用 : #{param} 预编译,防止 SQL 注入
  • 结果映射 : resultType 、别名、字段别名( as )
  • 主键回填 : useGeneratedKeys="true" 、 keyProperty="id"**

2.5 业务层(Service)

AdminService.java 示例

@Service
@Transactional
public class AdminService {
@Autowired
private AdminDao adminDao;
public PageResult<Admin> getAdminList(String account, String type, int page, int size) {
int offset = (page - 1) * size;
ArrayList<Admin> list = adminDao.getAdminList(account, type, offset, size);
int total = adminDao.getAdminCount(account, type);
return new PageResult<>(list, total);
}
public void add(Admin admin){
admin.setOperTime(new Date());
adminDao.add(admin);
}
public void update(Admin admin){
admin.setOperTime(new Date());
adminDao.update(admin);
}
public void delete(int id){
adminDao.delete(id);
}
}

**- @Service 注解 :标记为业务层组件

  • @Transactional 注解 :事务管理(原子性、一致性、隔离性、持久性)
  • @Autowired 注解 :依赖注入(DI)
  • 分页逻辑 : offset = (page - 1) * size
  • 业务处理 :设置操作时间等**

2.6 控制层(Controller)

AdminController.java 示例

@RestController

@RequestMapping(path = "/admin")

public class AdminController {

@Autowired

private AdminService adminService;

@GetMapping(path = "/list")

public Result list(@RequestParam(required = false) String account,

@RequestParam(required = false) String type,

@RequestParam(defaultValue = "1") int page,

@RequestParam(defaultValue = "10") int size) {

PageResult<Admin> pageResult = adminService.getAdminList(account, type, page, size);

return new Result(200, "查询成功", pageResult);

}

@PostMapping(path = "/add")

public Result add(@RequestBody Admin admin){

adminService.add(admin);

return new Result(200,"添加成功",null);

}

@PutMapping(path = "/update")

public Result update(@RequestBody Admin admin){

adminService.update(admin);

return new Result(200,"更新成功",null);

}

@DeleteMapping(path = "/delete/{id}")

public Result delete(@PathVariable int id){

adminService.delete(id);

return new Result(200,"删除成功",null);

}

}

-**RESTful 风格 :

  • @GetMapping :查询
  • @PostMapping :新增
  • @PutMapping :更新
  • @DeleteMapping :删除
  • 参数绑定 :
  • @RequestParam :查询参数
  • @RequestBody :请求体(JSON)
  • @PathVariable :路径变量
  • 统一返回结果 :Result 类封装状态码、消息、数据**

第三阶段:前端开发

3.1 Vue.js 基础

核心概念:

Vue.js = 渐进式 JavaScript 框架

响应式数据 + 组件化

Vue 实例结构

export default {

name: 'AdminList',

data() {

return {

// 响应式数据

}

},

created() {

// 生命周期钩子:创建后

},

methods: {

// 方法

}

}

3.2 Element UI 组件库

**常用组件

  • 表单 : el-form 、 el-input 、 el-select 、 el-button
  • 表格 : el-table 、 el-table-column
  • 分页 : el-pagination
  • 对话框 : el-dialog
  • 消息提示 : el-message 、 el-confirm**

3.3 Axios HTTP 请求

api/admin.js 示例

import request from '@/utils/request'

export function getAdminList(params) {
return request({
url: '/admin/list',
method: 'get',
params: params
})
}

export function addAdmin(data) {
return request({
url: '/admin/add',
method: 'post',
data: data
})
}

**- 请求方法 :GET、POST、PUT、DELETE

  • 参数传递 :
  • params :URL 查询参数(GET)
  • data :请求体(POST/PUT)**

3.4 代理配置解决跨域

vue.config.js

module.exports = {
devServer: {
port: 8081,
proxy: {
'/': {
target: 'http://localhost:8080',
changeOrigin: true
}
}
}
}

跨域原理:

前端 (8081) → 代理 → 后端 (8080)

浏览器同源策略

代理服务器转发

第四阶段:数据库设计与 SQL

4.1 表结构设计

admin 表

CREATE TABLE admin (

id INT PRIMARY KEY AUTO_INCREMENT,

account VARCHAR(50) NOT NULL UNIQUE,

password VARCHAR(50) NOT NULL,

type TINYINT DEFAULT 1 COMMENT '0-超级管理员,1-普通管理员',

gender VARCHAR(10) DEFAULT '男',

phone VARCHAR(20),

adminid INT,

oper_time DATETIME DEFAULT CURRENT_TIMESTAMP

);

-**主键 : PRIMARY KEY 、 AUTO_INCREMENT

  • 唯一约束 : UNIQUE
  • 默认值 : DEFAULT
  • 注释 : COMMENT**

4.2 SQL 语句

查询(带条件和分页):

select * from admin

where account like '%admin%' and type = 1

order by id desc

limit 0, 10

插入:

insert into admin (account, password, type, gender, phone, oper_time)

values ('test', '123456', 1, '男', '13800138000', NOW())

更新:

update admin

set account = 'newadmin', password = '654321'

where id = 1

删除:

delete from admin where id = 1

相关推荐
野犬寒鸦1 小时前
ArrayList扩容机制深度解析(附时序图详细讲解)
java·服务器·数据结构·数据库·windows·后端
逆境不可逃2 小时前
【从零入门23种设计模式03】创建型之建造者模式(简易版与导演版)
java·后端·学习·设计模式·职场和发展·建造者模式
汤姆yu2 小时前
基于springboot的健身爱好者打卡与互动交流系统
java·spring boot·后端
jaysee-sjc3 小时前
十三、Java入门进阶:异常、泛型、集合与 Stream 流
java·开发语言·算法
百锦再3 小时前
Java Map常用方法和实现类深度详解
java·开发语言·spring boot·struts·kafka·tomcat·maven
_codemonster3 小时前
JavaWeb开发系列(九)idea配置jdbc
java·ide·intellij-idea
Hx_Ma163 小时前
测试题(六)
java·tomcat·mybatis
人道领域3 小时前
SpringBoot vs SpringMVC:以及SpringBoot的全流程开发(1)
java·spring boot·spring
码云数智-大飞3 小时前
.NET 10 & C# 14 新特性详解:扩展成员 (Extension Members) 全面指南
java·数据库·算法