SpringBoot学习(未完)

基础入门

快速运行SpringBoot

在pom.xml中导入对应的依赖

    <!--导入springboot-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
    </parent>

    <dependencies>
        <!--导入web开发场景-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

创建一个springboot的主函数

package com.xzh.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @Author XuZhuHong
 * @CreateTime 2021/6/7 12:03
 * @SpringBootApplication 生命这是一个springboot应用
 */
@SpringBootApplication
public class MainApplicationContext {
    public static void main(String[] args) {
        SpringApplication.run(MainApplicationContext.class,args);
    }
}

创建控制层

package com.xzh.boot.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author XuZhuHong
 * @CreateTime 2021/6/7 12:05
 */
//这个注解是ResponseBody和Controller的合体
@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String handle01(){
        return "Hello, Spring Boot 2!";
    }
}

运行springboot主方法

浏览器访问对应的地址

http://localhost:8080/hello

成功

在这里插入图片描述

如何打包

导入插件

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

在这里插入图片描述

怎么运行:
进入到jar包的文件夹
启动cmd
然后输入命令 java -jar 文件名几IU可以启动项目了

application.properties文件配置

文件可以配置哪些东西 可以参考官方文档
所有的配置都在这个里面

关于主程序的注解

//这个注解是导入对应的类到ioc容器中
@Import({User.class, DBHelper .class} )
//这个注解表示是不是说有容器都用一个实例  false表示不是  true表示是
@Configuration( proxyBeanMethods = false)
//这个是根据条件创建  bean
@ConditionalOnMissingBean(name = "tom" )
//这个是导入Bean的Xml配置文件
@ImportResource("classpath: beans . xm1" )

开发小技巧

针对javaBean的lombok

导入对应的包

 <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

然后再idea中添加lombok的插件
在这里插入图片描述
关于他的几个注解:

//lombok的注解自动生成get,set方法
@Data
//自动生成tostring
@ToString
//自动生成构造方法(全部参)
@AllArgsConstructor
//自动生成无参构造方法
@NoArgsConstructor
//重写HashCode方法
@EqualsAndHashCode
@Component
//读取application.properties里面person开头的配置
@ConfigurationProperties(prefix = "person")
public class Person {
    private String sex;
    private Integer age;
}


热更新的依赖dev-tools

在pom.xml假如依赖就可以了


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

怎么使用代码更新后 Ctrl+F9就更新了

快速创建一个springboot的神器Spring Initailizr

在idea中new一个porject
在最右侧选择Spring Initailizr

在这里插入图片描述
在这个页面选择自己需要用到的场景
比如web mysql mybatis

在这里插入图片描述

他会自动引入依赖和创建初始的项目结构

yaml(yml)配置文件

基本语法:

key: value;kv之间有空格
大小写敏感
使用缩进表示层级关系
缩进不允许使用tab,只允许空格
缩进的空格数不重要,只要相同层级的元素左对齐即可
'#‘表示注释
字符串无需加引号,如果要加,’'与""表示字符串内容 会被 转义/不转义

• 字面量:单个的、不可再分的值。date、boolean、string、number、null

k: v

对象:键值对的集合。map、hash、set、object

行内写法:  k: {k1:v1,k2:v2,k3:v3}
#或
k: 
  k1: v1
  k2: v2
  k3: v3

数组:一组按次序排列的值。array、list、queue

行内写法:  k: [v1,v2,v3]
#或者
k:
 - v1
 - v2
 - v3

怎么读取:

@Value方式

在需要的变量上面添加这个注解
如下 ${ }里面的值对应的是配置文件里的key

name: NAME
@Value("${name}")
private String name1;

数组方式比较特别

arraylist: [a,b,c,d,e]
@Value("${arraylist[0]}")
    private String arraylist;

Environment

首先需要有一个Environment类的变量 springBoot会自动注入

	@Autowired
    private Environment env;

然后直接调用方法即可:

System.out.println(env.getProperty("name"));
System.out.println(env.getProperty("arraylist[0]"));

字符串的值和value注解注入规则一样

@ConfigurationProperties

实例:
Person类:

package com.xzh.boot12.bean;

import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

//下面的代码由Lombok提供
//@Data  自动生成get,set方法
@Data
//@ToString  自动生成tostring注解
@ToString
//@AllArgsConstructor  自动生成构造方法(全部参)
@AllArgsConstructor
//@NoArgsConstructor  自动生成无参构造方法
@NoArgsConstructor
//@EqualsAndHashCode  重写HashCode方法
@EqualsAndHashCode
//@ConfigurationProperties绑定配置文件key为person的数据   
//用这个注解过后里面的数据有变量名和配置key相等时会自动注入
@ConfigurationProperties(prefix = "person")
@Component//放到容器中的注解
public class Person {
    private String userName;
    private Boolean boss;
    private Date birth;
    private Integer age;
    private String[] interests;
    private List<String> animal;
    private Map<String, Object> score;
    private Set<Double> salarys;
}

/**
注意想要使用上面关于lombok的注解必须要在pom.xml中导入以下代码:
<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
</dependency>
*/


application.yml配置文件:

# yaml表示以上对象
person:
  userName: zhangsan
  boss: false
  birth: 2019/12/12 20:12:33
  age: 18
  interests: [ 篮球,游泳 ]
  animal:
    - jerry
    - mario
  score:
    english:
      first: 30
      second: 40
      third: 50
    math: [ 131,140,148 ]
    chinese: { first: 128,second: 136 }
  salarys: [ 3999,4999.98,5999.99 ]

解决编写配置文件没有提示的问题

  <!--yaml编写提示-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>



 <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <!--这句话的意思是 让这个打包插件 不要把yaml的代码提示放进去-->
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configuration-processor</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

WEB开发

静态资源访问

只要静态资源放在类路径下: called /static (or /public or /resources or /META-INF/resources
访问 : 当前项目根路径/ + 静态资源名

改变默认的静态资源路径

spring:
  mvc:
    #这里是改变他的访问地址
    static-path-pattern: /res/**
    #这个东西会影响 springboot的自定义欢迎页面失效

  resources:
    #这里是改变他默认的静态资源路径
    static-locations: [classpath:/haha/]

redis风格开启

在配置文件中开启:
这里实在yml中开启的

spring:
  mvc:
    hiddenmethod:
      filter:
        enabled: true

然后在controller中设置对应的请求方式

    //    @RequestMapping(value = "/user",method = RequestMethod.GET)
    @GetMapping("/user")
    public String getuser() {
        return "getuser user";
    }

    //    @RequestMaping(value = "/user", method = RequestMethod.POST)
    @PostMapping ("/user")
    public String postuser() {
        return "postuser user";
    }

    //    @RequestMapping(value = "/user", method = RequestMethod.DELETE)
    @DeleteMapping("/user")
    public String deleteuser() {
        return "deleteuser user";
    }

    //    @RequestMapping(value = "/user", method = RequestMethod.PUT)
    @PutMapping("/user")
    public String putuser() {
        return "putuser user";
    }

需要注意的是 请求方式必须是post 需要在表单中有一个name为_method value为所提交方法的标签 这里可以设置成hidden 控制层才能正确调用

<h1>欢迎页面</h1>
<form method="get" action="/user">
    <input type="submit" value="get">
</form>
<form method="post" action="/user">
    <input type="submit" value="post">
</form>
<form method="post" action="/user">
    <input name="_method" type="hidden" value="delete">
    <input type="submit" value="delete">
</form>
<form method="post" action="/user">
    <input name="_method" type="hidden" value="put">
    <input type="submit" value="put">
</form>

想要改变name的值可以通过以下方式

@Configuration(proxyBeanMethods = false)
public class WebConfig {
    @Bean
    public HiddenHttpMethodFilter hiddenHttpMethodFilter(){
        HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
        //这个是设置那个name的名字
        hiddenHttpMethodFilter.setMethodParam("_m");
        return hiddenHttpMethodFilter ;
    }
}

常用注解

请求地址为: http://localhost:8080/car/3/owner/lisi?ge=18&inters=basketball&inters=game

@PathVariable(路径变量)

代码为:

@RestController
public class ParameterTestController {
    @GetMapping("/car/{id}/owner/{username}")
    public Map< String, Object > getCar(@PathVariable("id") Integer id,
                                        @PathVariable("username") String username,
                                        @PathVariable Map< String, Object > pv)
                                        //省略代码
                                        }

当他指定了值得时候 就会把rest风格请求的参数 传递到对应的变量上
如果没有指定 ,那么就会把所有的rest风格参数用Map的方式存储

@RequestHeader(获取请求头)

获取请求头的参数 具体的用法参照上面的 返回和获取和上面的一样
只不过这个注解是用来获取请求头参数

@RequestParam(获取请求参数)

用来获取问号后面的一些参数的值,也可以封装到map中,但是有一点要注意的是,如果用户提交的是复选框,就会有相同名字的key,这里就需要单独提取出来,用List数组保存
如下 请求地址为:
http://localhost:8080/car/3/owner/lisi?age=18&inters=basketball&inters=game
代码为:

@GetMapping("/car/{id}/owner/{username}")
    public Map< String, Object > getCar(@RequestParam("inters") List<String> inters,
                                        @RequestParam Map< String, Object > rp) {
        Map< String, Object > map = new HashMap<>();
        map.put("rp", rp);
        map.put("inters", inters);
        return map;
    }

但是map集合中只有一个inters值
在这里插入图片描述
所以需要用List集合保存多个name相同的数据
在这里插入图片描述
保存在List集合中后 再添加到Map集合中就可以了

@CookieValue(获取cookie值)

这个注解后面必须跟一个值 (@CookieValue(“valiu”) String ck) 值就是cookie的名字
只能赋值到String或者Cookie类型的变量中

@RequestBody(获取请求体[POST])

这个注解必须要放在post请求的方法上面
获取请求地址中 ? 后的值 可以用String接收

@RequestAttribute(获取request域属性)

@RequestAttribute(“msg”) Object msg;
等同于:
Object msg=request.getAttribute(“msg”)

@MatrixVariable(矩阵变量)

矩阵变量需要在SpringBoot中手动开启
根据RFC3986的规范,矩阵变量应当绑定在路径变量中!
若是有多个矩阵变量,应当使用英文符号;进行分隔。
若是一个矩阵变量有多个值,应当使用英文符号,进行分隔,或之命名多个重复的key即可。
如:/cars/sell;low=34;brand=byd,audi,yd

要想使用这个矩阵变量的注解
必须要先在配置类中开启它

@Configuration(proxyBeanMethods = false)
public class WebConfig   {
    @Bean
    public HiddenHttpMethodFilter hiddenHttpMethodFilter(){
        HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
        //这个是设置那个name的名字
        hiddenHttpMethodFilter.setMethodParam("_method");
        return hiddenHttpMethodFilter ;
    }


    //开启MatrixVariable(矩阵变量)注解的使用
    @Bean
    public  WebMvcConfigurer webMvcConfigurerAdapter() {
        return new WebMvcConfigurer() {
            @Override
            public void configurePathMatch(PathMatchConfigurer configurer) {
                UrlPathHelper urlPathHelper = new UrlPathHelper();
                urlPathHelper.setRemoveSemicolonContent(false);
                configurer.setUrlPathHelper(urlPathHelper);
            }
        };
    }
}

Controller层代码:

    // /cars/sell;low=34;brand=byd,audi,yd
    @GetMapping("/cars/{path}")
    public Map carsSellet(@MatrixVariable("low") Integer low,
                          @MatrixVariable("brand") List<String> brand,
                          @PathVariable("path") String pv){
        Map<String , Object> map =new HashMap<>();
        map.put("low" ,low);
        map.put("brand", brand);
        map.put("pv", pv);
        return map;
    }

如果遇到这种请求 参数相同的 // /boss/1;age=20/2;age=10
可以通过再设置一个pathVar 来区分

@GetMapping("/boss/{bossId}/{empId}")
    public Map bossSellet(@MatrixVariable(value = "age", pathVar = "bossId") Integer bossAge,
                          @MatrixVariable(value = "age", pathVar = "empId") Integer empAge) {
        Map< String, Object > map = new HashMap<>();
        map.put("bossAge", bossAge);
        map.put("empAge", empAge);
        return map;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值