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

快速入门,springboot知识点汇总

学习 springboot 应该像学习一门编程语言一样,首先要熟练掌握常用的知识,而对于不常用的内容可以简单了解一下。先对整个框架和语言有一个大致的轮廓,然后再逐步补充细节。

前序:

Spring Boot 通过简化配置和提供开箱即用的特性,大大加快了 Spring 应用的开发过程。

1、构建一个 Spring Boot 项目

打开idea, 选择新建项目, 生成器选择spring initiallzr, 类型选择Maven, 然后点击下一步, 依赖项可以选个spring web

在这里插入图片描述

整个 项目结构 如下

myproject
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── example
│   │   │           └── myproject
│   │   │               └── MyprojectApplication.java
│   │   └── resources
│   │       └── application.properties
└── pom.xml

正常初始化一个项目时, 我们还需要导入很多依赖, 而且过程很繁琐

而maven就可以简化这个导入依赖这个过程,我们可以通过 Maven 配置文件(pom.xml),减少了依赖管理的复杂性。

2、导入依赖

进入 maven官网, 在搜索框中可以搜索到我们需要的依赖。

比如我们搜索 Spring Boot Starter JDBC这个依赖, 选择版本号, 把下面的代码粘贴到pom.xml文件中的dependencies标签中就算是导入依赖。(记得刷新才可以)
在这里插入图片描述

2.1 常用依赖

下面是一些常用到的依赖

  1. MySQL Connector/J

MySQL 官方提供的 JDBC 驱动程序,用于 Java 应用程序与 MySQL 数据库之间的连接和通信。

  1. Spring Boot Starter JDBC

可以快速地配置和使用 JDBC 数据库连接。通俗的来说, 我们引入这个依赖后就可以快速的让程序连接到数据库, 并且通过代码来编写sql语句, 控制数据库。

连接数据库:
我们可以通过在application.properties配置文件中配置如下信息就可以连接到数据库

spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  1. Project Lombok

可以让我们通过注解来减少样板代码的编写, 样板代码一般来说就是pojo类的get, set, 构造函数 ,equals,hashCode,toString等等。(下面会讲到pojo类)

  1. mybatis-plus-boot-startermybatis-plus-generator

MyBatis-Plus相关的依赖。

MyBatis-Plus 提供了一套通用的 Mapper 接口,通过继承这些接口,能够实现对单表的 CRUD 操作,无需编写重复的 SQL 语句。(相当于是它帮我们写好了很多mapper层的接口, 下面会讲到mapper)

如果加入上面两个mybatisplusspring不能正常使用mybatisplus的话可以加入这个依赖mybatis-spring

  1. spring-boot-starter-security

Spring Security 的相关依赖

Spring Security 是一个功能强大且高度可定制的身份验证和访问控制框架。通过简单的配置和注解,开发者可以实现复杂的身份验证和授权逻辑,保护应用程序的安全。也就是说通过它我们可以轻松的实现web上登录注册。

可以在下面讲到的时候再添加这个依赖, 不然要登录才能访问

3、 应用的关键层次和功能

POJO 层定义数据对象和封装数据。
Mapper 层与数据库交互,执行数据操作。
Service 层处理业务逻辑,调用 Mapper 层实现数据操作。
Controller 层接收和处理用户请求,调用 Service 层获取数据并返回响应。

我们一般会在myproject(上面层级结构中的)文件夹下分别创建pojomapperservicecontroller文件夹, 然后在文件夹中写java类

下面的样例代码中会出现很多注解, 它具体什么作用可自行查阅, 不同注解具体什么作用直接背过就行了, 初学阶段不要深究!!!

  1. pojo

pojo中文件名(pojo类名)一般定义成和数据库中的表名相同,一般把变量名定义成和该表中的字段名相同,这样springboot就会自动的把这个pojo和类的变量直接映射到数据库中对应的表和列中。

这样外部要访问数据库就可以通过这个pojo类的get,set方法获取修改该pojo类对应的数据库中的表。 但是每个pojo类都要写这些方法难免会有些繁琐, 我们可以通过上面下载的依赖Project Lombok来自动完成, 只需要在pojo类上面写上@Data @NoArgsConstructor @AllArgsConstructor这三个注解, 这个依赖就会自动帮我们生成

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {private Long id;private String username;private String email;// Getters and setters// toString, equals, hashCode 因为有上面三个注解, 所以会自动生成, 不需要手写
}
  1. Mapper

类名和表名相同, 实现不同表的基本sql查询,包括增删改查等操作。
(上面讲的MyBatis-Plus写好的有很多接口, 我们只需要继承MyBatis-Plus写好的接口就行, 可以参考 MyBatis-Plus官网 )

@Mapper
public interface UserMapper {@Select("SELECT * FROM users WHERE id = #{id}")User findById(Long id);// 其他 SQL 操作方法
}
  1. Service

调用 Mapper 层的方法进行数据访问,处理返回结果并进行适当的业务处理。类名根据具体的业务定义。

@Service
public class UserService {@Autowiredprivate UserMapper userMapper;public User getUserById(Long id) {return userMapper.findById(id);}// 其他业务逻辑方法
}
  1. Controller

接收来自客户端的 HTTP 请求, 也就是不同url调用不同的函数, 函数对应着业务的逻辑

根据业务逻辑 调用相应的 Service 层方法, 然后把处理结果返回,通常返回 JSON、HTML 页面或其他格式的数据。

@RestController
public class UserController {@Autowiredprivate UserService userService;@GetMapping("/users/{id}")public User getUserById(@PathVariable Long id) {return userService.getUserById(id);}// 其他请求处理方法
}

4、Spring Security

添加这个依赖后, 访问网站就需要登录验证

4.1 JWT认证

在 Web 应用中,JWT 常用于实现用户身份认证和授权。特别是在客户端和服务器之间安全地传输信息。

下面简单介绍一下jwt的工作原理:
客户端向服务器发送请求, 服务器用 客户端发来的用户信息(比如userid) 和 自身的密钥(可以看成是一堆字符串)拼接成一个字符串, 然后通过加密算法得到一个新的字符串, 这个新的字符串就是jwt, 然后服务器会把这个jwt返回给客户端,
之后客户端的所有请求都需要带上jwt, 当服务器接收到时会用用户信息 和 自身 密钥 通过加密算法得到一个jwt, 然后判断该请求所带的jwt是否相同。 虽然jwt存在用户本地, 但是用户不知道服务器的密钥, 即使修改jwt也没用, 所以通过jwt验证是安全的

4.2 JWT准备工作

上面讲的 jwt 生成验证等过程的实现网上有很多写好的类, 我们直接引用到项目中使用就行, 初学阶段还是以用为主, 至于为什么这样写, 暂且不用管。 下面是我找到的~

  1. JwtUtil类用来创建、解析jwt token
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;@Component
public class JwtUtil {public static final long JWT_TTL = 60 * 60 * 1000L * 24 * 14;  // 有效期14天public static final String JWT_KEY = "SDFGjhdsfalshdfHFdsjkdsfds121232131afasdfac";public static String getUUID() {return UUID.randomUUID().toString().replaceAll("-", "");}public static String createJWT(String subject) {JwtBuilder builder = getJwtBuilder(subject, null, getUUID());return builder.compact();}private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;SecretKey secretKey = generalKey();long nowMillis = System.currentTimeMillis();Date now = new Date(nowMillis);if (ttlMillis == null) {ttlMillis = JwtUtil.JWT_TTL;}long expMillis = nowMillis + ttlMillis;Date expDate = new Date(expMillis);return Jwts.builder().id(uuid).subject(subject).issuer("sg").issuedAt(now).signWith(secretKey).expiration(expDate);}public static SecretKey generalKey() {byte[] encodeKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);return new SecretKeySpec(encodeKey, 0, encodeKey.length, "HmacSHA256");}public static Claims parseJWT(String jwt) throws Exception {SecretKey secretKey = generalKey();return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(jwt).getPayload();}
}
  1. JwtAuthenticationTokenFilter用来验证jwt token,如果验证成功,则将User信息注入上下文中
import io.jsonwebtoken.Claims;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {@Autowiredprivate UserMapper userMapper;@Overrideprotected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {String token = request.getHeader("Authorization");if (!StringUtils.hasText(token) || !token.startsWith("Bearer ")) {filterChain.doFilter(request, response);return;}token = token.substring(7);String userid;try {Claims claims = JwtUtil.parseJWT(token);userid = claims.getSubject();} catch (Exception e) {throw new RuntimeException(e);}User user = userMapper.selectById(Integer.parseInt(userid));if (user == null) {throw new RuntimeException("用户名未登录");}UserDetailsImpl loginUser = new UserDetailsImpl(user);UsernamePasswordAuthenticationToken authenticationToken =new UsernamePasswordAuthenticationToken(loginUser, null, null);SecurityContextHolder.getContext().setAuthentication(authenticationToken);filterChain.doFilter(request, response);}
}
  1. SecurityConfig类用来放行登录、注册等接口
import JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;@Configuration
@EnableWebSecurity
public class SecurityConfig {@Autowiredprivate JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}@Beanpublic AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {return authConfig.getAuthenticationManager();}@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.csrf(CsrfConfigurer::disable) // 基于token,不需要csrf.sessionManagement((session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) // 基于token,不需要session.authorizeHttpRequests((authz) -> authz.requestMatchers("/user/account/token/", "/user/account/register/").permitAll() // 放行api.requestMatchers(HttpMethod.OPTIONS).permitAll().anyRequest().authenticated()).addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);return http.build();}
}

暂时更新到这里… 过几天有时间再更

http://www.lryc.cn/news/397199.html

相关文章:

  • Ubuntu20.04系统非root用户安装GAMIT10.71
  • stm32 开发板可以拿来做什么?
  • latex英文转中文word,及一些latex相关工具分享
  • EasyOCR: 简单易用的多语言OCR工具
  • arm架构安装chrome
  • ETAS工具导入Com Arxml修改步骤
  • Apache Kylin模型构建全解析:深入理解大数据的多维分析
  • element-plus的文件上传组件el-upload
  • 等保测评视角下的哈尔滨智慧城市安全框架构建
  • Java中的数据缓存技术及其应用
  • SQL 索引
  • free第一次成功,第二次失败
  • 各种音频处理器
  • 深度学习探秘:Transformer模型跨框架实现大比拼
  • 京准电钟:云计算中NTP网络时间服务器的作用是什么?
  • Apache中使用CGI
  • 宏任务与微任务对比【前端异步】
  • Autogen和LangGraph对比
  • uniapp vue3微信小程序如何获取dom元素
  • Mongodb索引使用限制
  • 阿里云通义千问开源两款语音基座模型分别是SenseVoice和CosyVoice
  • 第11章 规划过程组(二)(11.10制订进度计划)
  • 如何在Spring Boot中集成Hibernate
  • Grind 75 | 3. merge two sorted lists
  • MyBatis(35)如何在 MyBatis 中实现软删除
  • C# 预处理器指令
  • Perl编译器架构:前端与后端的精细分工
  • 14-63 剑和诗人37 - 分布式系统中的数据访问设计
  • 大数据基础:Hadoop之MapReduce重点架构原理
  • 人工智能算法工程师(中级)课程3-sklearn机器学习之数据处理与代码详解