# SPringBootdemo023 **Repository Path**: wuhuan11/spring-bootdemo023 ## Basic Information - **Project Name**: SPringBootdemo023 - **Description**: SPringBootdemo023 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2022-09-22 - **Last Updated**: 2022-09-27 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Java框架开发 **项目介绍:** - view层,视图根据接受到的数据最终展示页面给用户浏览。 - controller层= Struts2的Action [二者区别 ]( [(12条消息) controller 和 Action 之间的区别_dieyu2828的博客-CSDN博客](https://blog.csdn.net/dieyu2828/article/details/101873799) ) ,**响应用户请求,决定使用什么视图、需要准备什么数据来显示**。 controller控制器通过接收前端传过来的参数进行业务操作,在返回一个指定的路径或者数据表直接调用Service,Service调用Mapper - service层, 存放业务逻辑处理,也是一些关于数据库处理的操作,但不是直接和数据库打交道,他有接口还有接口的实现方法,在接口的实现方法中需要导入mapper层,mapper层是直接跟数据库打交道的,他也是个接口,只有方法名字,具体实现在mapper.xml文件里,service是供我们使用的方法。 service的impl文件将Mapper和Service进行整合 - model层=entity层=pojo层,存放我们的实体类,与数据库中的属性值基本保持一致。 [三者区别 ](https://www.jianshu.com/p/2f104f70d862) - mapper层=dao层,对数据库进行**数据持久化操作**(把数据放到持久化的介质中,同时提供增删改查操作), 他的方法语句直接针对数据库操作 。 mapper的接口对应resources下的xml文件,它只有方法名,封装了对数据库进行的数据持久化操作。 # 一、SpringBoot简介 ## 1.1 原有Spring优缺点分析 ## 1.2 SpringBoot的概述 ### 1.2.1 SpringBoot解决上述Spring的缺点 SpringBoot对上述Spring的缺点进行的改善和优化,基于约定优于配置的思想,可以让开发人员不必在配置与逻辑业务之间进行思维的切换,全身心的投入到逻辑业务的代码编写中,从而大大提高了开发的效率,一定程度上缩短了项目周期。 ### 1.2.2 SpringBoot的特点 ### 1.2.3 SpringBoot的核心功能 - 起步依赖 起步依赖本质上是一个Maven项目对象模型(Project Object Model,POM),定义了对其他库的传递依赖,这些东西加在一起即支持某项功能。 简单的说,起步依赖就是将具备某种功能的坐标打包到一起,并提供一些默认的功能。 - 自动配置 Spring Boot的自动配置是一个运行时(更准确地说,是应用程序启动时)的过程,考虑了众多因素,才决定Spring配置应该用哪个,不该用哪个。该过程是Spring自动完成的。 ## 1.3 入门程序 https://start.spring.io/ ### 1.3.1 SpringBoot入门程序 优势 ``` 1.起步依赖 本质上是一个Maven的项目对象模型(Project object model),定义了对其他的传递依赖,这些东西加在一起即支持某项功能。也就是说起步依赖将某种功能坐标打包到一起,并提供一些默认功能。 2.自动配置 ``` > 1.创建项目(可以选webapp) ![QQ截图20201016134312](D:\Course\TrainingPro\课程文档\pic\QQ截图20201016134312.png) > 2.添加依赖 ``` spring-boot-starter-parent org.springframework.boot 2.3.1.RELEASE org.example SpringBootInit1016 1.0-SNAPSHOT 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-autoconfigure 2.3.1.RELEASE ``` ``` starter-web负责整合spring和springmvc的坐标 ``` 注意:plugins作用是给出构建过程需要用到的插件https://blog.csdn.net/yeguxin/article/details/77110604 > 3.创建启动类 ```java @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } } ``` - SpringBootApplication为sb的启动类、**引导类**,main是程序入口。 - SpringApplication.run(MySpringBootApplication.class) 代表运行SpringBoot的启动类,run参数为SpringBoot启动类的字节码对象 > 4.创建处理器 ```java @RestController public class HelloController { @GetMapping("/hello") public String hello(){ return "hello"; } } ``` > 5 测试: ```java @SpringBootApplication @RestController组合注解=@Controller + @ResponseBody @GetMapping("hello") //映射路径 ``` Controller注解,表明了这个类是一个控制器类 。 ResponseBody表示方法的返回值直接以指定的格式写入Http response body中,而不是解析为跳转路径。 **如果要求方法返回的是json格式数据,而不是跳转页面,可以直接在类上标注@RestController** 。 https://blog.csdn.net/qq_40147863/article/details/84194493 ``` banner下载和application.properities一个目录 -----https://bootschool.net/ascii ``` [(springboot 配置 tomcat_](https://blog.csdn.net/lxw_hk2_zy/article/details/121140220) > 关于artifact的解释: > > 1. Artifact 是maven中的一个概念,表示某个module要如何打包 , 例如war exploded、war、jar、ear等等这种打包形式; 一个module有了 Artifacts 就可以部署到应用服务器中了! > > 2. explode 在这里你可以理解为展开,不压缩的意思。也就是war、jar等产出物没压缩前的目录结构。 扩展: [区分IDEA中的project、module、facet、artifact、Library、JAR和WAR_](https://suprit.blog.csdn.net/article/details/113095307?spm=1001.2101.3001.6650.5&utm_medium=distribute.pc_relevant.none-task-blog-2~default~OPENSEARCH~Rate-5-113095307-blog-114099691.pc_relevant_multi_platform_whitelistv3&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~OPENSEARCH~Rate-5-113095307-blog-114099691.pc_relevant_multi_platform_whitelistv3&utm_relevant_index=10) ### 1.3.2 SpringBoot工程热部署 我们在开发中反复修改类、页面等资源,每次修改后都是需要重新启动才生效,这样每次启动都很麻烦,浪费了大量的时间,我们可以在修改代码后不重启就能生效,在 pom.xml 中添加如下配置就可以实现这样的功能,我们称之为热部署。 ```xml ``` 然后 Shift+Ctrl+Alt+/,选择Registry ### 1.3.3 使用idea快速创建SpringBoot项目 https://blog.csdn.net/m0_58574228/article/details/122638887 ## 1.4 SpringBoot原理分析 ### 1.4.1 分析spring-boot-starter-parent 按住Ctrl点击pom.xml中的spring-boot-starter-parent,跳转到了spring-boot-starter-parent的pom.xml,xml配置如下(只摘抄了部分重点配置): ```xml org.springframework.boot spring-boot-dependencies 2.0.1.RELEASE ../../spring-boot-dependencies ``` 按住Ctrl点击pom.xml中的spring-boot-starter-dependencies,跳转到了spring-boot-starter-dependencies的pom.xml,xml配置如下(只摘抄了部分重点配置): ```xml ``` 从上面的spring-boot-starter-dependencies的pom.xml中我们可以发现,一部分坐标的版本、依赖管理、插件管理已经定义好,所以我们的SpringBoot工程继承spring-boot-starter-parent后已经具备版本锁定等配置了。所以起步依赖的作用就是进行依赖的传递。 ### 1.4.2 分析spring-boot-starter-web 按住Ctrl点击pom.xml中的spring-boot-starter-web,跳转到了spring-boot-starter-web的pom.xml,xml配置如下(只摘抄了部分重点配置): ```xml ``` 从上面的spring-boot-starter-web的pom.xml中我们可以发现,spring-boot-starter-web就是将web开发要使用的spring-web、spring-webmvc等坐标进行了“打包”,这样我们的工程只要引入spring-boot-starter-web起步依赖的坐标就可以进行web开发了,同样体现了依赖传递的作用。 ### 1.4.3 自动配置原理解析 - 这部分解释4.1的拦截器、国际化为什么会起作用 按住Ctrl点击查看启动类MySpringBootApplication上的注解@SpringBootApplication ```java @SpringBootApplication public class MySpringBootApplication { public static void main(String[] args) { SpringApplication.run(MySpringBootApplication.class); } } ``` 注解@SpringBootApplication的源码 ```java @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) public @interface SpringBootApplication { /** * Exclude specific auto-configuration classes such that they will never be applied. * @return the classes to exclude */ @AliasFor(annotation = EnableAutoConfiguration.class) Class[] exclude() default {}; ... ... ... } ``` 其中, @SpringBootConfiguration:等同与@Configuration,既标注该类是Spring的一个配置类 @EnableAutoConfiguration:SpringBoot自动配置功能开启 按住Ctrl点击查看注解@EnableAutoConfiguration ```java @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage @Import(AutoConfigurationImportSelector.class) public @interface EnableAutoConfiguration { ... ... ... } ``` 其中,@Import(AutoConfigurationImportSelector.class) 导入了AutoConfigurationImportSelector类 按住Ctrl点击查看AutoConfigurationImportSelector源码 ```java public String[] selectImports(AnnotationMetadata annotationMetadata) { ... ... ... List configurations = getCandidateConfigurations(annotationMetadata, attributes); configurations = removeDuplicates(configurations); Set exclusions = getExclusions(annotationMetadata, attributes); checkExcludedClasses(configurations, exclusions); configurations.removeAll(exclusions); configurations = filter(configurations, autoConfigurationMetadata); fireAutoConfigurationImportEvents(configurations, exclusions); return StringUtils.toStringArray(configurations); } protected List getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { List configurations = SpringFactoriesLoader.loadFactoryNames( getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader()); return configurations; } ``` 其中,SpringFactoriesLoader.loadFactoryNames 方法的作用就是从META-INF/spring.factories文件中读取指定类对应的类名称列表 ![](pic\11.png) spring.factories 文件中有关自动配置的配置信息如下: ``` ... ... ... org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\ ... ... ... ``` 上面配置文件存在大量的以Configuration为结尾的类名称,这些类就是存有自动配置信息的类,而SpringApplication在获取这些类名后再加载 我们以ServletWebServerFactoryAutoConfiguration为例来分析源码: ```java @Configuration @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) @ConditionalOnClass(ServletRequest.class) @ConditionalOnWebApplication(type = Type.SERVLET) @EnableConfigurationProperties(ServerProperties.class) @Import({ ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class, ServletWebServerFactoryConfiguration.EmbeddedTomcat.class, ServletWebServerFactoryConfiguration.EmbeddedJetty.class, ServletWebServerFactoryConfiguration.EmbeddedUndertow.class }) public class ServletWebServerFactoryAutoConfiguration { ... ... ... } ``` 其中, @EnableConfigurationProperties(ServerProperties.class) 代表加载ServerProperties服务器配置属性类 进入ServerProperties.class源码如下: ```java @ConfigurationProperties(prefix = "server", ignoreUnknownFields = true) public class ServerProperties { /** * Server HTTP port. */ private Integer port; /** * Network address to which the server should bind. */ private InetAddress address; ... ... ... } ``` 其中, prefix = "server" 表示SpringBoot配置文件中的前缀,SpringBoot会将配置文件中以server开始的属性映射到该类的字段中。映射关系如下: ![](pic\12.png) # 二、SpringBoot与整合其他技术 ## 2.0 MVC项目数据库对比 ```xml ``` ## 2.1 SpringBoot整合Mybatis ### 2.1.1 添加Mybatis的起步依赖 整合MyBatis Step1: ```xml org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.0 ``` - 添加数据库驱动坐标 ```xml mysql mysql-connector-java ``` ### 2.1.2 添加数据库连接信息 Step2:application-dev.yaml中添加数据量的连接信息,因为在application.yaml中配置了active: dev,所以生产环境不用管 ```yaml spring: #数据源配置 datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=GMT%2B8&useSSL=false username: root password: root hikari: maximum-pool-size: 2 minimum-idle: 2 #mybatis配置 mybatis: #mapper配置文件 config-location: classpath:mybatis-config.xml mapper-locations: classpath:mapper/*.xml type-aliases-package: cn.edu.neu.springbootdemo.model ``` 注意:需要在test1数据库中创建user表 ### 2.1.3 创建实体Bean Step3:接下来创建model层的User实体类 ```java package cn.edu.neu.springbootdemo.model; public class User { private int userid; private String username; private String password; private String realname; private String birthdate; private String gender; private String interest; private String degree; private String intro; public int getUserid() { return userid; } public void setUserid(int userid) { this.userid = userid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRealname() { return realname; } public void setRealname(String realname) { this.realname = realname; } public String getBirthdate() { return birthdate; } public void setBirthdate(String birthdate) { this.birthdate = birthdate; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getInterest() { return interest; } public void setInterest(String interest) { this.interest = interest; } public String getDegree() { return degree; } public void setDegree(String degree) { this.degree = degree; } public String getIntro() { return intro; } public void setIntro(String intro) { this.intro = intro; } @Override public String toString() { return "User [userid=" + userid + ", username=" + username + ", password=" + password + ", realname=" + realname + ", birthdate=" + birthdate + ", gender=" + gender + ", interest=" + interest + ", degree=" + degree + ", intro=" + intro + "]"; } } ``` 另外(为了方便使用先把lombok导入) ```xlm org.projectlombok lombok ``` User实体类 ```java package cn.edu.neu.springbootdemo.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor //无参构造和全参构造可以不加 public class User { private int userid; private String username; private String password; private String realname; private String birthdate; private String gender; private String interest; private String degree; private String intro; @Override //重写toString public String toString() { return "User [userid=" + userid + ", username=" + username + ", password=" + password + ", realname=" + realname + ", birthdate=" + birthdate + ", gender=" + gender + ", interest=" + interest + ", degree=" + degree + ", intro=" + intro + "]"; } } ``` ### 2.1.4 编写Mapper 注意:@Mapper标记该类是一个mybatis的mapper接口,可以被spring boot自动扫描到spring上下文中 Step4:与启动类同一级别创建mapper文件夹并创建UserMapper接口 ```java package cn.edu.neu.springbootdemo.mapper; import java.util.List; import org.apache.ibatis.annotations.Mapper; import cn.edu.neu.springbootdemo.core.common.Page; import cn.edu.neu.springbootdemo.model.User; import org.springframework.stereotype.Repository; @Mapper//使用@Mapper注解,表示这是操作数据库的mapper,SpringBoot自动扫描 //也可以在启动类里使用MapperScan("cn.edu.neu.springbootdemo.mapper")注解,参数是包名,一个效果 // Dao层,所以可以使用@Repository,当然也可以使用Component注解,不写也OK public interface UserMapper { List getUserList(User user);//查 User existsUser(User user); int existUser(User user); void addUser(User user); //增 User getUser(String userid); void updateUser(User user);//改 boolean deleteUser(User user); //删 List getUserListWithPage(Page page); //List getUserListWithPageNo(Page page); } ``` ### 2.1.5 配置Mapper映射文件 Step5:在resources下创建mapper文件夹,并创建UserMapper.xml文件 Mybatis中文文档官网:https://mybatis.net.cn/getting-started.html 其中: > 1. namespace必须与@Mapper注解的Mapper接口的**全类名**一致 > 2. xml文件名必须与@Mapper注解的**接口名一致** > 3. 标签中的id必须与@Mapper注解的的接口中的**方法名一致,且参数一致** 这里需要确认: 整合对应application-dev.yaml里type-aliases-package别名扫描包、mapper-locations 定义mapper位置 ,即加载Mybatis映射文件 ```mysql ``` ### 2.1.6 定义controller Step6:定义service(以getUserList为例) service.impl.UserServiceImpl ```java @Service //使用@Service注解,SpringBoot自动扫描 public class UserServiceImpl implements UserService{ @Autowired private UserMapper mapper; @Override public List getUserList(User user) { // TODO Auto-generated method stub return mapper.getUserList(user); } } ``` Step7:定义controller ```java @Controller @RequestMapping("/user") public class UserAction { @Autowired private UserService userService; @RequestMapping("/getUserList") public String getUserList(User user, Map> m){ System.out.println(user); List userList=userService.getUserList(user); m.put("userList", userList); System.out.println("m:"+m); return "/user/userList"; } } ``` ### 2.1.7 测试 测试: http://localhost:8080/springbootdemo/user/getUserList ## 2.2 SpringBoot整合Junit ### 2.2.1 添加Junit的起步依赖 ```xml org.springframework.boot spring-boot-starter-test test ``` ### 2.2.2 编写测试类 ```java import com.itheima.MySpringBootApplication; import com.itheima.domain.User; import com.itheima.mapper.UserMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest(classes = MySpringBootApplication.class) public class MapperTest { @Autowired private UserMapper userMapper; @Test public void test() { List users = userMapper.queryUserList(); System.out.println(users); } } ``` 其中, SpringRunner继承自SpringJUnit4ClassRunner,使用哪一个Spring提供的测试测试引擎都可以 ```java public final class SpringRunner extends SpringJUnit4ClassRunner ``` @SpringBootTest的属性指定的是引导类的字节码对象 测试: 查看控制台打印信息 ### ```java ``` # 三、员工管理系统MVC版 # 四、员工管理系统SpringBoot版 ## 4.0 关于Thymeleaf ## 4.1 common文件夹介绍 - ## 4.2 关于首页静态资源 - ## 4.3 首页HomeAction - ## 4.4 首页 ## 4.5 登录 ## 4.6 用户列表页 - ## 4.7 修改 - ## 4.8 删除 - 用户列表页userList点击删除,执行@{/user/deleteUser(userid=${user.userid})} user/result.html ```html ``` ## 4.9 Action - action/UserAction ```java ``` - HomeAction ```java ``` - BaseAction里的代码没有用 完整代码在:C:\Users\everi\Desktop\Code\train2022\springbootdemo0915 ## 4.10 打包部署 •1. File->Project Structure •2. Project Settings -> Artifacts -> 点击 + 号 -> JAR -> From modules with dependencies •3. 点击文件图标 -> 选择入口类 -> OK ->OK •4. idea右侧点击[maven](https://so.csdn.net/so/search?q=maven&spm=1001.2101.3001.7020) -> 点击Lifecycle下的clean -> 点击package •5. 通过控制台INFO查看jar包位置 •6. cmd运行 进入到命令行方式:java -jar jar文件 ## 五 基本Git操作 ### 5.1 基本环境配置 - 1.安装Git ​ 在Windows上使用Git,可以从Git官网直接下载安装程序进行安装。 ​ 测试命令:git --version 使用 where git 命令,就可以查看git安装位置。 - 2.注册码云账号 - 3.点击码云头像--设置--SSH公钥--点击生成/添加SSH公钥 ``` https://gitee.com/help/articles/4181 ``` 按照提示完成三次回车,即可生成 ssh key。通过查看 `~/.ssh/id_ed25519.pub` 文件内容,获取到你的 public key 。使用编辑器打开,复制到码云中,权限认证之后即可添加完成。 - 测试公钥:打开终端,输入命令 ssh -T git@gitee.com - **加密:公钥加密私钥解密** - **认证:私钥加密公钥解密** ``` 1.B将自己公钥给A 2.B将文件用自己私钥加密传送给A 3.A根据B的公钥解密,如果成功则为真实身份用户 ``` ### 5.2 创建仓库托管项目 - 在Idea里配置Git 地址https://blog.csdn.net/ningdjdj/article/details/123781541 VCS---- checkout from version control --------Git 查看状态:git status 查看修改过的与新增的文件内容 添加暂存区:git add . 将所有代码提交到本地仓库:git commit –m “提交m消息” 切换分支:git checkout master 查看分支:git branch 在master分支进行代码合并:git merge login 远程推送:git push 把本地分支推送云端保存:git checkout login git push –u origin login 创建分支:git checkout –b login 查看分支:git branch