Springboot 笔记

本人收藏来自互联网的JavaScript笔记,仅供学习自用(⊙o⊙)哦!

  • 格式:
    • 大标题
      – 小标题
      – 链接

专业术语

Interceptor 	拦截器  (核心在于该接口:HandlerInterceptor,然后重写其方法)
拦截器执行顺序:preHandle -> controller -> postHandle -> afterCompletion,同时需要注意的是,只有 preHandle 方法返回 true,后面的方法才会继续执行。

filter				过滤器 (抛出异常不会被Exception捕获,只能在自己的异常那里捕获...待定)
先过滤 再拦截



前后端分离访问template目录下的html文件 项目报404尝试重启项目和idea

在spring boot项目中resources/static目录下的文件可通过浏览器直接访问,而resources/templates下的HTML不能通过浏览器直接访问,而需要Spring
Mvc这样的框架映射到那个页面地址。

href=“/common/main.html”
/ 代表从服务器根目录 如果项目路径名设为rentcar,则路径为localhost:8080/rentcar/common/main.html,如果没有设置项目名,则为localhost:8080/common/main.html

前后端数据交互

JSON中只有字符串和数字  
https://segmentfault.com/a/1190000022589383
       问题:当前台向后台用json格式传值的时候
                如果传参数 X值的为 null,到后台接受X的变量为 "null"。
                如果没有传参数 X,后台接受X的变量为 null。
       解决:后端判断  if (!"null".equals(balance)&& balance!=null)
	还有其他方法待定

RequestParam 用来处理Content-Type: 为 application/x-www-form-urlencoded编码的一个参数 (默认编码)
RequestBody 接收的是一个Json对象的字符串 


@ResponseBody 返回json格式数据 但在前端会自动转为js对象 {id:001,...}
// JSON字符串{"id":"001",...}
 
/api/integrate/admin/update/{id}/{money} 用这种方式可以不用判空  如果少了参数就不会请求到这个路径
	@GetMapping("getFileList")
    public Result getFileList(@RequestParam("page") int currentPage,
                              @RequestParam("limit") int pageSize,
                              @RequestParam(required = false) String userId,
                              @RequestParam(required = false) String uploadTime,
                              @RequestParam(required = false) String tagId) {

        File file = new File();
        // 判断某字符串是否为不为空,为空的标准是str == null 或 str.length() == 0 即空字符串 ""
        if (StrUtil.isNotEmpty(userId))
            file.setUserId(Integer.valueOf(userId));

        if (StrUtil.isNotEmpty(tagId))
            file.setTagId(Integer.valueOf(tagId));
        
        file.setUploadTime(uploadTime);        

        Page<FileVo> filePage = fileService.selectByPage(currentPage, pageSize, file);

        int total = (int) filePage.getTotal();
        List<FileVo> list = filePage.getRecords();
        return Result.success(list, total);

    }

下面的有点问题 待解决
接受参数时类型会自动转换,然后格式不对则会为null (记得一定使用包装类型)
比如常用 String => Integer 比如实体类的字段类型为 Integer

	@GetMapping("getFileList")
    public Result getFileList(@RequestParam("page") int currentPage,
                              @RequestParam("limit") int pageSize,
                              @RequestParam(required = false) Integer userId,
                              @RequestParam(required = false) String uploadTime,
                              @RequestParam(required = false) Integer tagId) {

SpringBoot中前后端数据交互

【参考:SpringBoot中前后端数据交互 - 潘_磊 - 博客园

当前端以application/x-www-form-urlencoded格式上传数据时,后台可以使用**@RequestParam或者不使用任何注解来获取参数**。 后台不可以使用@RquestBody来获取参数,使用的话会报错误。

当前端使用**application/json(即使用JSON字符串)**来传递数据的时候,后端只能使用
@RequestBody 以及 Java bean
或者 map 的方式来接收数据。


【参考:SpringBoot 前后端json数据交互_beidaol的博客-CSDN博客


自定义返回信息格式

service层返回Result类型

简单的业务可以直接在controller层处理,如登录等


@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result implements Serializable   {
		private String code; 	//0为失败,1为成功
        private boolean success;	// 是否成功
        private String msg;			// 返回信息
        private object data;

        public Result success(String msg, object  data){
        		this.code= 1;
                this.success = true;
                this.msg = msg;
                this.data = data;
        }
		public Result fail( String msg, object  data){
        		this.code= 0;
                this.success = false;
                this.msg = msg;
                this.data = data;
        }
        public Result error(String msg, object  data){
        		this.code= 0;
                this.success = false;
                this.msg = msg;
                this.data = data;
        }
}

自定义参数不够使用时采用map
比如Layui表格需要传 总数据条数


@RequestMapping("/update")
@ResponseBody
public Map<String, Object> update() {
    Map<String, Object> map = new HashMap<>();
    List<Object> data= new ArrayList<>();
    // list里套list
    // List<List<Object>> listdata = new ArrayList<>(); 
	map.put("msg", "修改成功");
    map.put("success", true);
    map.put("data", data);
    map.put("...", ...);
    return map;

技巧

1.实体类用包装类修饰属性,当不传该属性参数时为null,默认不更新!

//例如
private String status;
private Double money;
private Integer id;

文件上传

【参考:SpringBoot实现本地存储文件上传及提供HTTP访问服务 - 掘金

 // 参考路径
      // file文件真实路径:C:\\Users\\Jarvis\\upload\\实拍CG结合 重点参考3.mp4
      // file文件访问路径:http://localhost:8080/upload/实拍CG结合 重点参考3.mp4

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile uploadFile, HttpServletRequest request) throws FileNotFoundException {
        //判断文件是否为空
        if (uploadFile.isEmpty()) {
            return Result.fail("上传文件不可为空");
        }

        // 用户的主目录 windows一般为C:/Users/xxx
        String fileDirPath = System.getProperty("user.home");

        //创建文件目录(如果没有的话)
        File fileDir = new File(fileDirPath+"/upload");
        if (!fileDir.isDirectory()) { //文件目录不存在,就创建一个
            fileDir.mkdirs();
        }

        //绝对路径
        String dir=fileDir.getAbsolutePath();
        try {
            // 获取上传文件的文件名
            String filename = uploadFile.getOriginalFilename();
            //服务端保存的文件对象
            File fileServer = new File(dir, filename);
            System.out.println("file文件真实路径:" + fileServer.getAbsolutePath());
            //2,实现上传
            uploadFile.transferTo(fileServer); //保存文件
            String filePath = request.getScheme() + "://" +
                    request.getServerName() + ":"
                    + request.getServerPort()
                    + "/upload/"
                    + filename;
            System.out.println("file文件访问路径:" + filePath);
            //3,返回可供访问的网络路径
            return Result.ok(filePath);


        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.fail("上传失败");
    }

改变文件上传路径和访问路径
mvc:/upload/**
resources加file:${user.home}/upload/

spring:
  servlet:
    multipart:
      max-file-size: 1GB
      max-request-size: 1GB
  devtools:
    livereload:
      enabled: true  # 热部署
  mvc:
    static-path-pattern: /upload/**  # 访问示例:http://localhost:8080/upload/xxx.mp4
  resources: # 注意,不是web层下
    static-locations: classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/templates/,file:${user.home}/upload/

流程

  • 访问http://localhost:8080/upload/xxx.mp4
  • 首先被spring.mvc.static-path-pattern拦截匹配该访问路径(/upload/**),然后去寻找文件,
  • spring.resources.static-locations里面配置了file文件路径,所以就到磁盘路径${user.home}/upload/里面找文件

配置

Spring Boot静态资源映射(以图片上传并显示为例)

spring.mvc.static-path-pattern

spring.mvc.static-path-pattern=/upload/**只有静态资源的访问路径为/upload/**时,才会处理请求。比如访问http://localhost:8080/upload/a.MP4,处理方式是据模式匹配后的文件名查找本地文件。

# 默认值
spring.mvc.static-path-pattern=/**

【spring boot】spring-boot中路径的配置
总结
spring.mvc.static-path-pattern:只会改变请问路径,资源还是放在默认的四个路径下

spring.resources.static-locations:不会改变访问路径,只是改变资源的放置路径

spring.resources.static-locations

spring.resources.static-locations自定义Springboot前端静态资源的位置。默认Springboot将从如下位置,按优先级查找静态资源:


# 默认值 访问路径不用加 static templates
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/ 

事务

【参考:Springboot + Mybatis-plus事务管理_bugpool的博客-CSDN博客

@Transactional默认回滚的是RuntimeException也就是说如果抛出的不是RuntimeException的异常,数据库是不会回滚的。但是所幸的是,在spring框架下,所有的异常都被org.springframework重写为RuntimeException,因此不需要太担心。但如果在异常发生时,程序员自己手动捕获处理了RuntimeException异常,事务也不会回滚。

SaToken

登录认证

所谓登录认证,说白了就是限制某些API接口必须登录后才能访问(例:查询我的账号资料)
那么如何判断一个会话是否登录?框架会在登录成功后给你做个标记,每次登录认证时校验这个标记,有标记者视为已登录,无标记者视为未登录!

默认自动会在浏览器上设置一个name为token,value为tokenValue的cookie
在这里插入图片描述

postman测试时需要带上token(或者cookie)
在这里插入图片描述


前后台分离(无Cookie模式)】app,小程序

请求头带上token即可,satoken会自动识别这个token,不过会在函数的最后再返回检查token(会先进入函数)

	@SaCheckLogin
    @PostMapping(value = "/video")
    private Result upLoadVideo(@RequestParam("file") MultipartFile file) throws IOException {
    	
	}

跨域问题

【参考:使用satoken[未能读取到有效Token]_satoken token无效_BBAA9527的博客-CSDN博客】 试过有用

【参考:使用 Sa-Token 的全局过滤器解决跨域问题_shengzhang_的博客-CSDN博客】 未尝试

打包

【参考:Maven: 在SpringBoot中加入第三方Jar包,并将其打包进自己的Jar包内_李先森LeeCode的博客-CSDN博客

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值