新版Spring Boot(5)- Spring Boot 整合 Web 开发(1)

1 JSON框架

3大主流框架:(1)jackson;(2)gson;(3)fastjson

  • Spring MVC中,jackson和gson已经自动配置好了
  • 序列化: 对象 -> JSON
  • 所有的JSON工具都会提供HttpMessageConverter

1.1 spring boot 整合 jackson

在这里插入图片描述

Jackson配置,有2种思路:

  1. 对象配置
  • @JsonProperty
  • @JsonIgnore@JsonIgnoreProperties
  • @JsonFormat,日期格式化,注意时区

  1. 全局配置
    自己提供 ObjectMapper
package com.tzb.thymeleafsprinboot.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.text.SimpleDateFormat;

/**
 * @Description TODO
 * @Author tzb
 * @Date 2021/7/18 11:02
 * @Version 1.0
 **/
@Configuration
public class WebMvcConfig {

    @Bean
    ObjectMapper objectMapper(){
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        return new ObjectMapper();
    }

}

1.3 spring boot整合 gson

1.4 spring boot整合 fastjson

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-json</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.73</version>
        </dependency>
  • 方法1
    在这里插入图片描述

在这里插入图片描述

  • Controller
@RestController
public class UserController {

    @GetMapping("/user")
    public User getUser(){
        User user = new User();
        user.setBirthday(new Date());
        user.setUsername("小旋风");
        return user;
    }

}


  • 方法2
    在这里插入图片描述

2 spring boot处理静态资源

  • 注意访问路径
    在这里插入图片描述
    在这里插入图片描述

  • 都可以存放静态资源,注意优先级
    在这里插入图片描述


在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2.1 静态资源位置的配置2种方式

3 单文件上传

在这里插入图片描述


在这里插入图片描述

  • Controller
package com.tzb.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Description TODO
 * @Author tzb
 * @Date 2021/8/14 21:07
 * @Version 1.0
 **/

@RestController
public class FileUploadController {

    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");


    @PostMapping("/upload")
    public String upload(MultipartFile file, HttpServletRequest request) {

        // 工程运行的临时目录
        String realPath = request.getServletContext().getRealPath("/");

        String format = sdf.format(new Date());
        String path = realPath + format;

        File folder = new File(path);

        if (!folder.exists()) {
            folder.mkdirs();
        }

        String oldName = file.getOriginalFilename();

        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));

        try {
            file.transferTo(new File(folder, newName));
            String s = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + format + newName;
            return s;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";

    }
}

  • 测试
    在这里插入图片描述
    在这里插入图片描述

4 多文件上传

4.1 方式1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="/upload2" method="post" enctype="multipart/form-data">
    <input type="file" name="files" multiple>
    <input type="submit" value="上传">
</form>

</body>
</html>

@RestController
public class FileUploadController2 {

    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");


    @PostMapping("/upload2")
    public void upload(MultipartFile[] files, HttpServletRequest request) {

        // 工程运行的临时目录
        String realPath = request.getServletContext().getRealPath("/");

        String format = sdf.format(new Date());
        String path = realPath + format;

        File folder = new File(path);

        if (!folder.exists()) {
            folder.mkdirs();
        }

        try {
            for (MultipartFile file : files) {
                String oldName = file.getOriginalFilename();

                String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));

                file.transferTo(new File(folder, newName));
                String s = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + format + newName;

                System.out.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

4.2 方式2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="/upload3" method="post" enctype="multipart/form-data">
    <input type="file" name="file1">
    <input type="file" name="file2">
    <input type="submit" value="上传">
</form>

</body>
</html>
@RestController
public class FileUploadController3 {

    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");


    @PostMapping("/upload3")
    public void upload(MultipartFile file1, MultipartFile file2, HttpServletRequest request) {

        // 工程运行的临时目录
        String realPath = request.getServletContext().getRealPath("/");

        String format = sdf.format(new Date());
        String path = realPath + format;

        File folder = new File(path);

        if (!folder.exists()) {
            folder.mkdirs();
        }

        try {
            String oldName1 = file1.getOriginalFilename();
            String newName1 = UUID.randomUUID().toString() + oldName1.substring(oldName1.lastIndexOf("."));
            file1.transferTo(new File(folder, newName1));
            String s1 = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + format + newName1;
            System.out.println(s1);

            String oldName2 = file2.getOriginalFilename();
            String newName2 = UUID.randomUUID().toString() + oldName2.substring(oldName2.lastIndexOf("."));
            file2.transferTo(new File(folder, newName2));
            String s2 = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + format + newName2;
            System.out.println(s2);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

5 spring boot + ajax 上传文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://code.jquery.com/jquery-3.6.0.js"
            integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
            crossorigin="anonymous"></script>
</head>
<body>

<div id="result">
    <input type="file" id="file">
    <input type="button" value="上传" onclick="uploadFile()">
</div>

<script>
    function uploadFile(){
        var file = $("#file")[0].files[0];
        var formData = new FormData();
        formData.append("file", file);

        $.ajax({
            type:'post',
            url:'/upload',
            processData:false,
            contentType:false,
            data: formData,
            success:function (msg){
                $("#result").html(msg);
            }
        })

    }
</script>

</body>
</html>
@RestController
public class FileUploadController {

    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");


    @PostMapping("/upload")
    public String upload(MultipartFile file, HttpServletRequest request) {

        // 工程运行的临时目录
        String realPath = request.getServletContext().getRealPath("/");

        String format = sdf.format(new Date());
        String path = realPath + format;

        File folder = new File(path);

        if (!folder.exists()) {
            folder.mkdirs();
        }

        String oldName = file.getOriginalFilename();

        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));

        try {
            file.transferTo(new File(folder, newName));
            String s = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + format + newName;
            return s;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值