Springboot学习笔记【持续更新中】

Springboot学习笔记【持续更新中】

SpringBoot2.x体系

**官网:**spring.io

学习目标:

  • 如何上手一门新技术[学会通过官网文档进行学习]
  • 构建springboot的知识体系
  • 学会通过springboot官方文档去学习后面更新版本新技术

1.环境准备:

  • 翻译工具:https://translate.google.cn/
  • springbootGitHub地址:https://github.com/spring-projects/spring-boot
  • springboot官方文档:https://spring.io/guides/gs/spring-boot/
  • 工具自动创建:http://start.spring.io/
  • 使用IDE 2018.2.1
  • jdk1.8
  • maven 3.5.2

学习新技术从quick start 入手

2.HTTP请求注解和简化注解

  • @RestController and @RequestMapping是springMVC的注解,不是springboot特有的
  • @RestController = @Controller+@ResponseBody
  • @SpringBootApplication = @Configuration+@EnableAutoConfiguration+@ComponentScan

3.JSON框架

3.1 常用框架

  • 阿里 Fastjson,
  • Jackson
  • 谷歌gson

3.2 FastJSON

1.源码和依赖

github:https://github.com/alibaba/fastjson

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.73</version>
</dependency>

2.常用API

3.3 Jackson

1.jackson处理相关自动

  • 指定别名:@JsonProperty
  • 空字段不返回:@JsonInclude(Include.NON_NUll)
  • 指定日期格式:@JsonFormat(pattern=“yyyy-MM-dd hh:mm:ss”,locale=“zh”,timezone=“GMT+8”)
  • 指定字段不返回:@JsonIgnore

4.HTTP接口GET请求

4.1 @GetMapping

@RestController
public class UserController {
   

    @GetMapping(value = "/getUserByName/{username}")
    public User getUserByName( @PathVariable("username") String username) {
   
        User user = new User(1, username, "892295771@qq.com", "15723254410");
        System.out.println(user.toString());
        return user;
    }

}
  • @GetMapping = @RequestMapping(method = RequestMethod.GET)
  • @PostMapping = @RequestMapping(method = RequestMethod.POST)
  • @PutMapping = @RequestMapping(method = RequestMethod.PUT)
  • @DeleteMapping = @RequestMapping(method = RequestMethod.DELETE)
  • @RequestMapping(path = “/{depid}/{userid}”, method = RequestMethod.GET) 可以同时指定多个提交方法

4.2 @RequestParam

@RequestParam(value = “name”, required = true)可以设置默认值,比如分页

    @GetMapping("/getUserById")
    public User getUserById(@RequestParam(value = "id",required = true,defaultValue = "1")String id){
   
        User user = new User(Integer.valueOf(id), "zx", "892295771@qq.com", "15723254410");
        return user;
    }
//访问路径:http://localhost:8080/getUserById?id=23
  • value:参数名
  • required:是否包含该参数,默认为true,表示该请求路径中必须包含该参数,如果不包含就报错。
  • defaultValue:默认参数值,如果设置了该值,required=true将失效,自动为false,如果没有传该参数,就使用默认值

4.3 @RequestBody

请求体映射实体类为json格式,需要指定http头为 content-type为application/json charset=utf-8

4.4 @RequestHeader

@RequestHeader 请求头

比如鉴权@RequestHeader("access_token") String accessToken

5.资源目录规范

5.1 资源目录

src/main/java:存放代码
src/main/resources
		static: 存放静态文件,比如 css、js、image, (访问方式 http://localhost:8080/js/main.js)
		templates:存放静态页面jsp,html,tpl
		config:存放配置文件,application.properties
	    resources:

….Springboot学习笔记【持续更新中】

如果把静态文件放到templates,需要引入thymeleaf依赖,同时需要创建一个controller进行跳转.

如果静态页面向直接跳转,需要把html放在springboot默认加载的文件夹下面。比如resource/static/public

Springboot学习笔记【持续更新中】

5.2 静态资源加载顺序

META/resources > resources > static > public 里面找是否存在相应的资源,如果有则直接返回。

1.默认配置

  • 官网地址:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-static-content
  • 自定义配置文件路径:spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

静态资源文件存储在CDN

6.文件上传

springboot文件上传 MultipartFile file,源自SpringMVC 【其本质就是流的传输】;

MultipartFile 对象的transferTo方法,用于文件保存(效率和操作比原先用FileOutStream方便和高效)

6.1 编写上传文件

静态页面存放位置:resources/static/upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>upload</title>
</head>
<body>
<h1>文件上传</h1>
<form action="/upload" enctype="multipart/form-data" method="post">
    文件:<input type="file" name="uploadFile"/>
    <br/>
    姓名:<input type="text" name="username"/>
    <br/>
    <input type="submit" value="上传">
</form>

</body>
</html>

6.2 后端接收


import com.example.springbootdemo.common.Rs;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

@RestController
@Slf4j
public class UploadController {
   

    @Value("${web.images-path}")
    private String path ;

    /** * 文件上传处理控制器 * * @param uploadFile * @param request * @return */
    @RequestMapping("/upload")
    public Rs upload(MultipartFile uploadFile, HttpServletRequest request) {
   
        //获取姓名参数
        String username = request.getParameter("username");
        System.out.println("姓名:" + username);

        //获取文件名称
        String originalFilename = uploadFile.getOriginalFilename();
        System.out.println("文件名称:"+originalFilename);
        //获取文件后缀名
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        System.out.println("文件后缀:"+suffixName);

        String fileName = UUID.randomUUID()+suffixName;
        System.out.println("转换后的文件名称:"+fileName);
       // String path = this.getClass().getClassLoader().getResource("").getPath();


        System.out.println("path:"+path);

        File file = new File(path,fileName);
        try {
   
            uploadFile.transferTo(file);
            return Rs.SUCCESS(path+fileName);
        }catch (Exception e){
   
            e.printStackTrace();
        }
        return Rs.FAILE("上传文件失败");
    }
}

application.properties

web.images-path=C:/Users/Administrator/Desktop/
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/test/,file:${web.upload-path} 

1.配置上传文件大小

文件大小配置,启动类里面配置或者专门建一个配置类或者配置文件中进行进行配置

@Bean  
public MultipartConfigElement multipartConfigElement() {
     
    MultipartConfigFactory factory = new MultipartConfigFactory();  
    //单个文件最大 
    factory.setMaxFileSize("10240KB"); //KB,MB 
    /// 设置总上传数据总大小 
    factory.setMaxRequestSize("1024000KB");  
    return factory.createMultipartConfig();  
}  

2.文件上传和访问需要指定磁盘路径

application.properties中增加下面配置
			1) web.images-path=C:/Users/Administrator/Desktop/
			2) spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/test/,file:${web.upload-path} 

7.打包成jar包

打包成jar包,需要增加maven依赖

 <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

GUI:反编译工具,作用就是用于把class文件转换成java文件

8.热部署

8.1 加入依赖

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-devtools</artifactId>
     <scope>runtime</scope>
     <optional>true</optional>
</dependency>

CTRL + F9 进行刷新 .同时需要对IDEA进行相关的配置,热部署才会起效果

1.setting配置

File–>settings—>compiler—>build project automatically

Springboot学习笔记【持续更新中】

2.打开Registry

使用快捷键:ctrl + shift + alt + / ,选中Registry...

Springboot学习笔记【持续更新中】

Springboot学习笔记【持续更新中】

3.修改启动类配置

Springboot学习笔记【持续更新中】
Springboot学习笔记【持续更新中】

9.配置文件注解

9.1 @Value(“${……}”)

配置文件自动映射到属性和实体类

@Value(“${test.name}”)
private String name;

9.2 @PropertySource(“{……}”)

Controller上面配置*@PropertySource({“classpath:resource.properties”})*

10.单元测试

11.自定义异常

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/100737.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 头文件cstring、string、string.h的区别「建议收藏」

    头文件cstring、string、string.h的区别「建议收藏」头文件cstring、string、string.h的区别<string>是C++标准库头文件,使用stirng类型必须首先包含string头文件,用于字符串操作,string类型可以进行+、=、+=、>等运算。std::string类实际上是STL模板类std::basic_string的具体化。#include<string>usingnamespacestd;strings;<cstring>是C标准库头文件<strin

    2025年9月3日
    5
  • flash做动画教程(基础篇)

    flash做动画教程(基础篇)第一步、软件的下载与安装FlashMX2004第二步、新建一个flash文档也就是场景一你可以右击空白的文档,作如下操作:一、改变文档的背景颜色二、根据自己制作gif动态图片的大小,来选择文档的宽高二、新建元件或者是导入外部图片有的图片是不需要自己加工的素材就从外部导入导入外部图片的步骤:文件-导入-导入到库-选择图片的位置…

    2022年4月28日
    60
  • c(多线程编程)

    c(多线程编程)c 多线程编程什么是多线程 相必有些程序或者计算机基础的就会有所了解 我就不做过多赘述了 确实不知道的 可以反手百度 线程开启方法之 委托线程开启 c 中开启多线程的方法之一 是调用委托的 BeginInvoke 方法 可以当即为该委托打开一个新的线程来跑其包含的方法 参数 BeginInvoke 方法有俩个默认的参数 如果当前委托是有参数的 那么委托的参数写在该方法默认参数的前面 判断线程状态 BeginInvoke 方法有个 IAsyncResult 类型的返回值 调用该返回值的 Is

    2025年12月9日
    3
  • Python入门习题(40)——CCF CSP认证考试真题:报数游戏「建议收藏」

    Python入门习题(40)——CCF CSP认证考试真题:报数游戏「建议收藏」CCFCSP认证考试真题(201712-2):游戏问题描述解题思路参考答案测试用例小结问题描述试题编号: 201712-2试题名称: 游戏时间限制: 1.0s内存限制: 256.0MB问题描述  有n个小朋友围成一圈玩游戏,小朋友从1至n编号,2号小朋友坐在1号小朋友的顺时针方向,3号小朋友坐在2号小朋友的顺时针方向,……,1号小朋友坐在n号小朋友的顺时针方向。  游戏开始,从1…

    2025年9月1日
    7
  • 菲尼克斯PSR-SCP- 24DC/FSP2/2X1/1X2耦合继电器

    菲尼克斯PSR-SCP- 24DC/FSP2/2X1/1X2耦合继电器菲尼克斯PSR-SCP-24DC/FSP2/2X1/1X2耦合继电器耦合继电器-PSR-SCP-24DC/FSP2/2X1/1X22986575适用于SIL2高需求和低需求应用的安全耦合继电器,将数字输出信号耦合至I/O端,2个启动电流通路,1个报警触点,用于安全状态关闭应用的模块,内置测试脉冲滤波器,插拔式螺钉连接端子,宽度:17.5mm产品类型 耦合继电器应用 安全关闭高要求低要求机械寿命 10×106开关次数继电器型号 带机械联锁触点的机电式继电器,符合IEC/EN6

    2022年6月22日
    28
  • 2015年度总结「建议收藏」

    2015年度总结「建议收藏」2015年度总结

    2022年4月24日
    43

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号