SpringBoot进阶使用

参考自 4.Web开发进阶.pptx^[1]^

静态资源访问

默认将静态资源放到src/main/resources/static目录下,这种情况直接通过ip:port/静态资源名称即可访问(默认做了映射)

也可以在application.properties 中通过spring.web.resources.static-locations进行设置

例如^[2]^,spring.web.resources.static-locations=/images/**,则必须在原路径前加上images

编译后resources下面的文件,都会放到target/classes下

文件上传

传文件时,(对前端来说)表单的enctype属性,必须由默认的application/x-www-form-urlencoded ,改为multipart/form-data,这样编码方式就会变化

`spring.servlet.multipart.max-file-size=10MB`^[3]^

src/main/java/com/example/helloworld/controller/FileUploadController.java^[4]^

package com.example.helloworld.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

@RestController
public class FileUploadController {

    @PostMapping("/upload")
    // 上面这行等价于 @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String up(String nickname, MultipartFile photo, HttpServletRequest request) throws IOException {
        System.out.println(nickname);
        // 获取图片的原始名称
        System.out.println(photo.getOriginalFilename());
        // 取文件类型
        System.out.println(photo.getContentType());

        // HttpServletRequest 获取web服务器的路径(可动态获取)
        String path = request.getServletContext().getRealPath("/upload/");
        System.out.println(path);
        saveFile(photo, path);
        return "上传成功";
    }

    //
    public void saveFile(MultipartFile photo, String path) throws IOException {
        //  判断存储的目录是否存在,如果不存在则创建
        File dir = new File(path);
        if (!dir.exists()) {
            //  创建目录
            dir.mkdir();
        }

        // 调试时可以把这个路径写死
        File file = new File(path + photo.getOriginalFilename());
        photo.transferTo(file);
    }
}

拦截器

就是一个中间件..

和gin的middleware完全一样

先定义一个普通的java类,一般以Interceptor结尾,代表是一个拦截器。需要继承系统的拦截器类,可以重写父类里的方法

父类基本没做啥事,空的方法实现

下面重写其中的方法

src/main/java/com/example/helloworld/interceptor/LoginInterceptor.java^[5]^

package com.example.helloworld.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("LoginInterceptor拦截!!!");
        return true;
    }
}

src/main/java/com/example/helloworld/config/WebConfig.java^[6]^

配置只拦截/user

package com.example.helloworld.config;

import com.example.helloworld.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/user/**");
    }


}

5.构建RESTful服务.pptx^[7]^

Spring Boot实现RESTful API

PUT和PATCH咋精确区分? ...前几年用过PUT,而PATCH我印象里从来没用过。。

没啥太大意思,还有主张一律用POST的 ​​​

src/main/java/com/example/helloworld/controller/UserController.java^[8]^:

package com.example.helloworld.controller;

import com.example.helloworld.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

@RestController
public class UserController {

    @ApiOperation("获取用户")
    @GetMapping("/user/{id}")
    public String getUserById(@PathVariable int id) {  // 想拿到路径上的动态参数,需要加@PathVariable 注解
        System.out.println(id);
        return "根据ID获取用户信息";
    }

    @PostMapping("/user")
    public String save(User user) {
        return "添加用户";
    }

    @PutMapping("/user")
    public String update(User user) {
        return "更新用户";
    }

    @DeleteMapping("/user/{id}")
    public String deleteById(@PathVariable int id) {
        System.out.println(id);
        return "根据ID删除用户";
    }
}

使用Swagger生成Web API文档

pom.xml^[9]^:

    <!-- 添加swagger2相关功能 -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
    <!-- 添加swagger-ui相关功能 -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>

除了添加依赖,还需要加一个配置类

src/main/java/com/example/helloworld/config/SwaggerConfig.java^[10]^:

package com.example.helloworld.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration // 告诉Spring容器,这个类是一个配置类(SB的配置类,都需要加上@Configuration这个注解)
@EnableSwagger2 // 启用Swagger2功能
public class SwaggerConfig {
    /**
     * 配置Swagger2相关的bean
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo()) // 调用了一个自定义方法(改改标题啥的~)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com"))// com包下所有API都交给Swagger2管理
                .paths(PathSelectors.any()).build();
    }

    /**
     * 此处主要是API文档页面显示信息
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("爽哥提示:演示项目API") // 标题
                .description("爽哥提示:演示项目") // 描述
                .version("1.0") // 版本
                .build();
    }
}

可以访问http://localhost:8080/swagger-ui.html^\[11\]^

读的项目里的控制器,展开可以看到每个控制器里都有什么方法

可以通过如下注解,在页面添加注释

例如@ApiOperation("获取用户")

还可以在页面直接进行调试

参考资料

[1]

4.Web开发进阶.pptx: https://github.com/cuishuang/springboot-vue/blob/main/课件/4.Web开发进阶.pptx
[2]

例如: https://github.com/cuishuang/springboot-vue/blob/main/SpringBoot代码/helloworld/src/main/resources/application.properties#L5
[3]

spring.servlet.multipart.max-file-size=10MB: https://github.com/cuishuang/springboot-vue/blob/main/SpringBoot代码/helloworld/src/main/resources/application.properties#L3
[4]

src/main/java/com/example/helloworld/controller/FileUploadController.java: https://github.com/cuishuang/springboot-vue/blob/main/SpringBoot代码/helloworld/src/main/java/com/example/helloworld/controller/FileUploadController.java
[5]

src/main/java/com/example/helloworld/interceptor/LoginInterceptor.java: https://github.com/cuishuang/springboot-vue/blob/main/SpringBoot代码/helloworld/src/main/java/com/example/helloworld/interceptor/LoginInterceptor.java
[6]

src/main/java/com/example/helloworld/config/WebConfig.java: https://github.com/cuishuang/springboot-vue/blob/main/SpringBoot代码/helloworld/src/main/java/com/example/helloworld/config/WebConfig.java
[7]

5.构建RESTful服务.pptx: https://github.com/cuishuang/springboot-vue/blob/main/课件/5.构建RESTful服务.pptx
[8]

src/main/java/com/example/helloworld/controller/UserController.java: https://github.com/cuishuang/springboot-vue/blob/main/SpringBoot代码/helloworld/src/main/java/com/example/helloworld/controller/UserController.java
[9]

pom.xml: https://github.com/cuishuang/springboot-vue/blob/main/SpringBoot代码/helloworld/pom.xml#L37
[10]

src/main/java/com/example/helloworld/config/SwaggerConfig.java: https://github.com/cuishuang/springboot-vue/blob/main/SpringBoot代码/helloworld/src/main/java/com/example/helloworld/config/SwaggerConfig.java
[11]

http://localhost:8080/swagger-ui.html: http://localhost:8080/swagger-ui.html

本文由mdnice多平台发布

相关推荐
计算机学姐2 小时前
基于python+django+vue的影视推荐系统
开发语言·vue.js·后端·python·mysql·django·intellij-idea
JustinNeil2 小时前
简化Java对象转换:高效实现大对象的Entity、VO、DTO互转与代码优化
后端
青灯文案12 小时前
SpringBoot 项目统一 API 响应结果封装示例
java·spring boot·后端
微尘83 小时前
C语言存储类型 auto,register,static,extern
服务器·c语言·开发语言·c++·后端
计算机学姐3 小时前
基于PHP的电脑线上销售系统
开发语言·vscode·后端·mysql·编辑器·php·phpstorm
码拉松4 小时前
千万不要错过,优惠券设计与思考初探
后端·面试·架构
白总Server5 小时前
MongoDB解说
开发语言·数据库·后端·mongodb·golang·rust·php
计算机学姐5 小时前
基于python+django+vue的家居全屋定制系统
开发语言·vue.js·后端·python·django·numpy·web3.py
程序员-珍6 小时前
SpringBoot v2.6.13 整合 swagger
java·spring boot·后端
海里真的有鱼6 小时前
好文推荐-架构
后端