Spring Boot(快速上手)

打印 上一主题 下一主题

主题 1004|帖子 1004|积分 3014

Spring Boot

零、情况设置

1. 创建项目



2. 热摆设

添加依赖:
  1. <dependency>
  2.     <groupId>org.springframework.boot</groupId>
  3.     <artifactId>spring-boot-devtools</artifactId>
  4.     <optional>true</optional>
  5. </dependency>
复制代码
设置application.properties文件:
  1. # 热部署生效
  2. spring.devtools.restart.enabled=true
  3. # 设置重启目录
  4. spring.devtools.restart.additional-paths=src/main/java
  5. # 设置classpath目录下的 WEB-INF 文件夹内容修改为不重启
  6. spring.devtools.restart.exclude=static/**
复制代码
打开设置,快捷方式CTRL + ALT + S,举行如下设置:

一、控制器

在Spring Boot中,控制器(Controller)是处置处罚HTTP请求和返回响应的组件。控制器是Spring MVC框架的一部门,用于实现模型-视图-控制器(MVC)设计模式中的控制器层。
SpringBoot提供了两种注解来表示此类负责继续和处置处罚 HTTP 请求:@Controller和@RestController,如果请求的是页面和数据,使用@Controller;如果只是请求数据,则可以使用@RestController。
默认情况下,@RestController注解会将返回的对象数据转换为JSON格式。
@RestController的使用方法
  1. @RestController                // 注解,表示该类是一个RestController控制器
  2. public class HelloController{
  3.     @RequestMapping("/user")        // 映射路由
  4.     public User getUser(){
  5.         User user = new User();
  6.         user.setUsername("zhangsan");
  7.         user.setPassword("123");
  8.         return user;
  9.     }
  10. }
  11. // 运行代码后,在浏览器中输入"localhost:8080/user"即可查看返回结果。
复制代码
  通常情况下,所写的控制器放在controller文件夹下。
  二、路由

注解 @RequsetMapping主要负责 URL 的路由映射,可以添加在Controller 类或者具体的方法上。如果添加 Controller 类上,则这个 Controller 中的所有路由映射都会加上此映射规则,如果添加在某个方法上,则只会对当前方法生效。
常用属性参数:


  • valuepath

    • 用途:定义请求的URL路径。
    • 阐明:value是@RequestMapping的属性,可以指定一个或多个URL路径。path是@RequestMapping的别名,与value功能雷同,但只能指定一个路径。

  • method

    • 用途:限制请求的HTTP方法(如GET、POST、PUT、DELETE等)。
    • 阐明:可以指定一个或多个HTTP方法,只有匹配这些方法的请求才会被映射到相应的处置处罚方法。

  • params

    • 用途:根据请求参数的存在与否来决定是否映射请求。
    • 阐明:可以指定一个或多个参数条件,只有当这些参数在请求中出现时,请求才会被映射。

  • headers

    • 用途:根据请求头的存在与否来决定是否映射请求。
    • 阐明:可以指定一个或多个请求头条件,只有当这些请求头在请求中出现时,请求才会被映射。

  • consumes

    • 用途:指定可继续的请求体的媒体类型(如application/json、text/plain等)。
    • 阐明:只有当请求的Content-Type与指定的媒体类型匹配时,请求才会被映射。

  • produces

    • 用途:指定控制器方法可以产生的媒体类型。
    • 阐明:这通常用于设置响应的Content-Type,告诉客户端期望接收的媒体类型。

  • name

    • 用途:为映射定义一个名称,方便在其他注解中引用。
    • 阐明:在大型应用中,使用名称可以简化映射的引用,进步代码的可维护性。

参数通报:


  • @RequestParam:用于将HTTP请求的查询字符串参数或请求体参数绑定到控制器方法的参数上。如果参数名称一致,可以省略。
  • @PathVariable:用于提取URL中的动态路径变量,并将这些变量通报给控制器方法的参数。
  • @RequestBody:用于接收请求体中的参数,通常用于处置处罚JSON、XML等非表单编码的数据。
实例:
  1. import org.springframework.web.bind.annotation.*;
  2. import xxx.start.entity.User;
  3. @RestController
  4. public class ParamsController {
  5.     @RequestMapping(value = "/getTest1", method = RequestMethod.GET)
  6.     public String getTest1(){
  7.         return "GET请求";
  8.     }
  9.     @RequestMapping(value = "/getTest2", method = RequestMethod.GET)
  10.     // 默认情况,方法的参数名要与网址传参的名称一致。
  11.     public String getTest2(String name, String phone){
  12.         System.out.println("name" + name);
  13.         System.out.println("phone" + phone);
  14.         return "GET请求";
  15.     }
  16.     @RequestMapping(value = "/getTest3", method = RequestMethod.GET)
  17.     // 传参的名称不对应,因此需要使用@RequestParam()进行指定,指定value的话,这样的话参数就必须进行传递,如果这个参数可传可不传就需要required参数
  18.     public String getTest3(@RequestParam(value = "name", required = false) String name){
  19.         System.out.println("name" + name);
  20.         return "GET请求";
  21.     }
  22.     // POST请求
  23.     @RequestMapping(value = "/postTest1", method = RequestMethod.POST)
  24.     public String postTest1(){
  25.         return "POST请求";
  26.     }
  27.     @RequestMapping(value = "/postTest2", method = RequestMethod.POST)
  28.     public String postTest2(String username, String password){
  29.         System.out.println("username" + username);
  30.         System.out.println("password" + password);
  31.         return "POST请求";
  32.     }
  33.     @RequestMapping(value = "/postTest3", method = RequestMethod.POST)
  34.     public String postTest3(User user){  // 这里直接使用User类进行接受,需要将User中的属性名称与传参名称保持一致!
  35.         System.out.println(user);
  36.         return "POST请求";
  37.     }
  38.     @RequestMapping(value = "/postTest4", method = RequestMethod.POST)
  39.     public String postTest4(@RequestBody User user){  // 处理请求体中的参数
  40.         System.out.println(user);
  41.         return "POST请求";
  42.     }
  43.     @RequestMapping(value = "/test/**")  // 正则表达式,**可以表示多层而*只能表示一层
  44.     public String test(){
  45.         return "通配符请求";
  46.     }
  47. }
复制代码
  GET方法通常情况是地点传参,如:http://localhost:8080/getTest2?name=张三&phone=123456,这样即将数据通报到了路由getTest2的方法中。
  三、文件上传

SpringBoot 工程嵌入的 tomcat 限制了请求的文件巨细,每个文件的设置最大为1MB,单次请求的文件总数不能大于10MB,如要更改默认设置,需要在 application.properties 文件中添加如下两个设置:
  1. # 上传的单个文件的大小
  2. spring.servlet.multipart.max-file-size=10MB
  3. # 上传的多个文件的大小
  4. spring.servlet.multipart.max-request-size=100MB
复制代码
实例:
  1. import org.springframework.web.bind.annotation.PostMapping;
  2. import org.springframework.web.bind.annotation.RestController;
  3. import org.springframework.web.multipart.MultipartFile;
  4. import javax.servlet.http.HttpServletRequest;
  5. import java.io.File;
  6. import java.io.IOException;
  7. @RestController
  8. public class FileUploadController {
  9.     @PostMapping("/upload")
  10.     public String up(String name, MultipartFile photo, HttpServletRequest request) throws IOException {
  11.         System.out.println(name);
  12.         // 获取图片原始名称
  13.         System.out.println(photo.getOriginalFilename());
  14.         // 获取文件类型
  15.         System.out.println(photo.getContentType());
  16.         // "user.dir"表当前工作目录的绝对路径
  17.         System.out.println(System.getProperty("user.dir"));
  18.         // 获取web服务器对应的路径,这里获取的是/upload文件夹的路径
  19.         String path = request.getServletContext().getRealPath("/upload/");
  20.         System.out.println(path);
  21.         saveFile(photo, path);
  22.         return "上传成功";
  23.     }
  24.     public void saveFile(MultipartFile photo, String path)throws IOException{
  25.         // 判断存储的目录是否存在
  26.         File dir = new File(path);
  27.         if(!dir.exists()){
  28.             // 如果不存在就创建目录
  29.             dir.mkdir();
  30.         }
  31.         File file = new File(path + photo.getOriginalFilename());
  32.         photo.transferTo(file);   // 写入到磁盘文件中
  33.     }
  34. }
复制代码
四、拦截器(Interceptor)

SpringBoot定义了HardlerInterceptor接口来实现自定义拦截器的功能。HandlerInterceptor接口定义了preHandle、postHandle、afterCompletion三种方法,通过重写这三种方法实现请求前、请求后等利用。


  • preHandle:在控制器(Controller)方法实行之前被调用。
  • postHandle:它在请求的控制器方法实行之后、渲染视图之前被调用。
  • afterCompletion:请求处置处罚流程的最后阶段被调用。
拦截器的使用分为两个步调:1. 定义,2. 注册。
   拦截器在定义时,将文件放置在interceptor文件夹中,使用时将文件放在config文件夹中。
  定义拦截器:
  1. import org.springframework.web.servlet.HandlerInterceptor;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. // 注册一个拦截器
  5. public class LoginInterceptor implements HandlerInterceptor {
  6.     @Override
  7.     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  8.         // 根据条件来判断是否进行拦截。
  9.         if("条件"){
  10.             System.out.println("通过");
  11.             return true;
  12.         }else{
  13.             System.out.println("不通过");
  14.             return false;
  15.         }
  16.     }
  17. }
复制代码
注册:


  • addPathPatterns:定义拦截的地点,添加的一个拦截器没有 addPathPattern 任何一个 URL 则默认拦截所有请求。
  • excludePathPatterns:定义排除某些地点不被拦截,如果没有 excludePathPatterns 任何一个请求,则默认不放过任何一个请求。
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    import xxx.start.interceptor.LoginInterceptor;
    // 设置类,可以供springboot来读,这里是添加一个拦截器
    @Configuration
    public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new LoginInterceptor()).addPathPatterns(“/user/**”);
    }
    }
五、RESTFUL

RESTFUL 是现在盛行的互联网软件服务架构设计风格。要求客户端使用GET、POST、PUT、DELETE四种表示利用方式的动词对服务端资源举行利用:


  • GET用于获取资源
  • POST用于新建资源(也可以用于更新资源)
  • PUT用于更新资源
  • DELETE用于删除资源。
RESTFUL 的特点:资源的表现形式是JSON或者HTML,客户端与服务端之间的交互在请求之间是无状态的,从客户端到服务端的每个请求都包含必须的信息。
   HTTP 状态码:
  

  • 1xx:信息,通过传输协议级信息。
  • 2xx:成功,表示客户端的请求已成功继续。
  • 3xx:重定向,表示客户端必须实行一些其他利用才能完成其请求。
  • 4xx:客户端错误,此类错误状态码指向客户端。
  • 5xx:服务器错误,服务器负责这些错误状态码。
  Spring Boot 实现 RESTFul API:


  • SpringBoot 提供的 spring-boot-starter-web 组件完全支持开辟RESTFUL API,提供了与REST利用方式(GET、POST、PUT、DELETE对应的注解)
注解
功能
@GetMapping
处置处罚 GET 请求,获取资源
@PostMapping
处置处罚 POST 请求,新增资源
@PutMapping
处置处罚 PUT 请求,更新资源
@DeleteMapping
处置处罚 DELETE 请求,删除资源
@PatchMapping
处置处罚 PATCH 请求,用于更新部门资源
实例:
  1. import io.swagger.annotations.ApiOperation;
  2. import org.springframework.web.bind.annotation.*;
  3. import xxx.start.entity.User;
  4. @RestController
  5. public class UserController {
  6.     @ApiOperation("根据ID获取用户信息")  // swagger的注解
  7.     @GetMapping("/user/{id}")
  8.     public String getUserById(@PathVariable int id){
  9.         System.out.println(id);
  10.         return "根据ID获取用户信息";
  11.     }
  12.     @PostMapping("/user")
  13.     public String save(User user){
  14.         return "添加用户";
  15.     }
  16.     @PutMapping("/user")
  17.     public String update(User user){
  18.         return "更新用户";
  19.     }
  20.     @DeleteMapping("/user/{id}")
  21.     public String deleteById(@PathVariable int id){
  22.         System.out.println(id);
  23.         return "根据ID删除用户";
  24.     }
  25. }
复制代码
六、Swagger

Swagger 是一个开源的 API 设计和文档工具,由 Tony Tam 于 2010 年创建,它可以帮助开辟人员更快、更简朴地设计、构建、文档化和测试 RESTful API。Swagger 可以自动生成交互式 API 文档、客户端 SDK、服务器 stub 代码等,从而使开辟人员更加轻易地开辟、测试和摆设 API 。
Swagger是一个规范和完备的框架,用于生成、形貌、调用和可视化RESTFul风格的web服务,是非常盛行的API表达工具。Swagger能够自动生成完善的RESTFul API文档,同时并根据背景代码的修改同步更新,同时提供完备的测试页面来调试API
使用方法:

  • 在项目中(pom.xml)引入 springfox-swagger2 和 springfox-swagger-ui 依赖即可。
    1. <!--        添加swagger2相关功能-->
    2. <dependency>
    3.     <groupId>io.springfox</groupId>
    4.     <artifactId>springfox-swagger2</artifactId>
    5.     <version>2.9.2</version>
    6. </dependency>
    7. <!--        添加swagger-ui相关功能-->
    8. <dependency>
    9.     <groupId>io.springfox</groupId>
    10.     <artifactId>springfox-swagger-ui</artifactId>
    11.     <version>2.9.2</version>
    12. </dependency>
    复制代码
  • 设置Swagger,需要在config目录中编写设置文件:
    1. import org.springframework.context.annotation.Bean;
    2. import org.springframework.context.annotation.Configuration;
    3. import springfox.documentation.builders.ApiInfoBuilder;
    4. import springfox.documentation.builders.PathSelectors;
    5. import springfox.documentation.builders.RequestHandlerSelectors;
    6. import springfox.documentation.service.ApiInfo;
    7. import springfox.documentation.spi.DocumentationType;
    8. import springfox.documentation.spring.web.plugins.Docket;
    9. import springfox.documentation.swagger2.annotations.EnableSwagger2;
    10. @Configuration    // 告诉Spring容器,这个类是一个配置类
    11. @EnableSwagger2    // 启用Swagger2功能
    12. public class SwaggerConfig {
    13.     /*
    14.     * 配置Swagger2相关的bean
    15.     * */
    16.     @Bean
    17.     public Docket createRestApi(){
    18.         return new Docket(DocumentationType.SWAGGER_2)
    19.                 .apiInfo(apiInfo())
    20.                 .select()
    21.                 .apis(RequestHandlerSelectors.basePackage("xxx"))
    22.                 .paths(PathSelectors.any()).build();
    23.     }
    24.     // 此处主要是API文档页面显示信息
    25.     private ApiInfo apiInfo(){
    26.         return new ApiInfoBuilder()
    27.                 .title("演示项目API")  // 标题
    28.                 .description("演示项目") // 描述
    29.                 .version("1.0")  // 版本
    30.                 .build();
    31.     }
    32. }
    复制代码
注意事项:


  • Spring Boot 2.6.x 之后与 Swagger 有版本冲突题目,需要在 application.properties 中加入以下设置:
    1. # 解决 swagger 版本与 springboot 版本不匹配的问题
    2. spring.mvc.pathmatch.matching-strategy=ant_path_matcher
    复制代码
使用 Swagger2 举行接口测试:


  • 启动项目之后,访问http://127.0.0.1:8080/swagger-ui.html即可打开自动生成的可视化测试页面。
七、MyBatis-Plus

友情链接:MyBatis-Plus 官方学习网址
MyBatis是一款优秀的数据持久ORM框架,被广泛地应用于系统,MyBatis 能够非常灵活地实现动态 SQL,可以使用 XML 或 注解 来设置和映射原生信息,能够轻松地将 JAVA 的 POJO(Plain Ordinary Java Object,普通的Java对象)与数据库中的表和字段举行映射关联。
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,它在 MyBatis 的底子上只做增强不做改变,旨在简化开辟和进步服从
使用方法:

  • 在pom.xml中添加依赖:
    1. <!-- MyBatisPlus依赖 -->
    2. <dependency>
    3.     <groupId>com.baomidou</groupId>
    4.     <artifactId>mybatis-plus-boot-starter</artifactId>
    5.     <version>3.4.2</version>
    6. </dependency>
    7. <!-- mysql驱动依赖 -->
    8. <dependency>
    9.     <groupId>mysql</groupId>
    10.     <artifactId>mysql-connector-java</artifactId>
    11.     <version>5.1.47</version>
    12. </dependency>
    13. <!-- 数据库链接池用于向数据库申请多个连接,提高数据库的连接效率 -->
    14. <dependency>
    15.     <groupId>com.alibaba</groupId>
    16.     <artifactId>druid-spring-boot-starter</artifactId>
    17.     <version>1.1.20</version>
    18. </dependency>
    复制代码
  • 在application.properties文件中设置数据库相干信息:
    1. # 连接数据库
    2. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    3. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    4. spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false
    5. spring.datasource.username=root
    6. spring.datasource.password=root
    7. mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
    8. #关闭mybatis-plus的自动驼峰命名法
    9. mybatis-plus.configuration.map-underscore-to-camel-case=false
    复制代码
  • 添加 @MapperScan 注解,在 StartApplication 文件(项目启动文件)中添加:
    1. package xxx.start;
    2. import org.mybatis.spring.annotation.MapperScan;
    3. import org.springframework.boot.SpringApplication;
    4. import org.springframework.boot.autoconfigure.SpringBootApplication;
    5. @SpringBootApplication
    6. @MapperScan("xxx/start/mapper")    // 使mapper包中的代码生效,mapper存放映射文件。
    7. public class StartApplication {
    8.     public static void main(String[] args) {
    9.         SpringApplication.run(StartApplication.class, args);
    10.     }
    11. }
    复制代码
  • 创建 mapper 文件夹,用于存放 mapper 类,在 mapper 文件夹中利用表的文件,文件名通常为:表名 + Mapper:
    1. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    2. import org.apache.ibatis.annotations.Insert;
    3. import org.apache.ibatis.annotations.Mapper;
    4. import org.apache.ibatis.annotations.Select;
    5. import xxx.start.entity.UserChart;
    6. import java.util.List;
    7. //@Repository
    8. @Mapper
    9. public interface UserMapper extends BaseMapper<UserChart> {   // 使用mybatisplus可以根据userchart表自动找到userchart表
    10. }
    复制代码
  • 使用 UserMapper 类,创建 UserMapperController 类:
    1. import org.springframework.beans.factory.annotation.Autowired;
    2. import org.springframework.web.bind.annotation.GetMapping;
    3. import org.springframework.web.bind.annotation.PostMapping;
    4. import org.springframework.web.bind.annotation.RestController;
    5. import xxx.start.entity.UserChart;
    6. import xxx.start.mapper.UserMapper;
    7. import java.util.List;
    8. // 数据库操作
    9. @RestController
    10. public class UserMappingController {
    11.     @Autowired(required = false)   // 会将mapper实例化出来的对象注入到userMapper中
    12.     private UserMapper userMapper;
    13.     @GetMapping("/usermap")
    14.     public List query(){
    15.         // 直接使用BaseMapper中自带的方法,selectList的值是查询条件,如果为 null 则表示查询全部。
    16.         List<UserChart> list = userMapper.selectList(null);
    17.         System.out.println(list);
    18.         return list;   // 返回给前端的数据
    19.     }
    20.     @PostMapping("/usermap")
    21.     public String save(UserChart userChart){
    22.         int i = userMapper.insert(userChart);
    23.         if(i > 0){
    24.             return "插入成功";
    25.         }else {
    26.             return "插入失败";
    27.         }
    28.     }
    29. }
    复制代码
  • UserChart 文件,是一个映射文件,用于映射数据库对应的表,放置到entity文件夹(自建文件夹)中:
    1. import com.baomidou.mybatisplus.annotation.IdType;
    2. import com.baomidou.mybatisplus.annotation.TableField;
    3. import com.baomidou.mybatisplus.annotation.TableId;
    4. import com.baomidou.mybatisplus.annotation.TableName;
    5. @TableName("userchart")
    6. // 另行说明表名为: userchart
    7. public class UserChart {
    8.     @TableId(type= IdType.AUTO)
    9.     // 表明id是自增的
    10.     public int id;
    11.     public String username;
    12.     public String password;
    13.     @TableField(value = "birth", exist = true)
    14.     // value表示对应数据库表中的具体字段,如果属性与字段不一致需要另行设置,exist表示该属性是否为字段,默认为true。
    15.     public String birthday;
    16.     public int getId() {
    17.         return id;
    18.     }
    19.     public void setId(int id) {
    20.         this.id = id;
    21.     }
    22.     public String getUsername() {
    23.         return username;
    24.     }
    25.     public void setUsername(String username) {
    26.         this.username = username;
    27.     }
    28.     public String getPassword() {
    29.         return password;
    30.     }
    31.     public void setPassword(String password) {
    32.         this.password = password;
    33.     }
    34.     public String getBirthday() {
    35.         return birthday;
    36.     }
    37.     public void setBirthday(String birthday) {
    38.         this.birthday = birthday;
    39.     }
    40.     @Override
    41.     public String toString() {
    42.         return "UserChart{" +
    43.                 "id=" + id +
    44.                 ", username='" + username + ''' +
    45.                 ", password='" + password + ''' +
    46.                 ", birthday='" + birthday + ''' +
    47.                 '}';
    48.     }
    49. }
    复制代码
八、目录结构



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

用多少眼泪才能让你相信

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表